Question

Am I missing something here?

class Foo;

class Bar {
    public:
        Foo foo;
};

class Foo { };

Error:

error C2079: 'Bar::foo' uses undefined class 'Foo'

Was it helpful?

Solution

When you forward-declare a class, you can make pointers and references to it, but you cannot make members of the type of forward-declared class: the full definition of Foo is needed to decide the layout of the outer class (i.e. Bar), otherwise the compiler cannot make a decision on the size and the structure of Bar.

This is allowed, though:

class Foo;

class Bar {
    public:
        Foo* fooPtr;
        Foo& fooRef;
};

The reason the pointers and references to forward-declared classes are allowed is that the sizes of pointers and references do not depend on the structure of the class to which they point (or which they reference).

OTHER TIPS

Yes you are missing something important: A question.

I assume you want to know what's wrong in the code, and why the compiler issues an error.

The compiler has to know the size of Foo in order to calculate the layout of the class Bar. The size of Foo objects is determined by their layout, to know that layout, the compiler has to know the class definition. At the point where you declare the Member variable foo, it merely knows that Foo exists, but not its size, because you have given it only a declaration, not a definition before.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top