Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining unnamed class member functions?

I currently have two unnamed classes defined in my Foo.h:

class Foo {
public:
    Foo();

    class {
    private:
        int x;
        int y;
    public:
        int GetX() { return x; }
        int GetY() { return y; }
    } Sub1;

    class {
    private:
        int x;
    public:
        int GetX() { return x; }
    } Sub2;
}

This code compiles just fine, and it used like this:

 Foo temp;
 int Ax, Ay, Bx;
 Ax = temp.Sub1.GetX();
 Ay = temp.Sub1.GetY();
 Bx = temp.Sub2.GetX();

However, now I want to move the member function definitions to the source file.The only way I know to split this class into a header file and source file, is to name the classes:

Foo.h:

class Foo {

private:    
    class A {
    private:
        int x;
        int y;
    public:
        int GetX();
        int GetY();
    };

    class B {
    private:
        int x;
    public:
        int GetX();
    };

public:
    Foo();
    A Sub1;
    B Sub2;

}

Foo.cpp:

int Foo::A::GetX() { return x; }
int Foo::A::GetY() { return y; }
int Foo::B::GetX() { return x; }

This code is not what I want, however, since it is ugly and I didn't want a named class in the first place.

Is it possible to split the class into a header file and source file? Or is this just bad code design?

like image 695
jvpernis Avatar asked May 20 '15 15:05

jvpernis


1 Answers

It is, unfortunately, impossible. §9.3/5:

If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the :: operator.

Since no class name exists, no out-of-class definitions for member functions are possible. The fact that GCC allows decltype-specifiers in this context is a bug.

like image 56
Columbo Avatar answered Sep 27 '22 23:09

Columbo