Reputation: 95000
int main() {
B bb; //does not compile (neither does class B bb;)
C cc; //does not compile
struct t tt; //compiles
class B {}; //HERE is the class B defination
struct s { struct t * pt; }; //compiles
struct t { struct s * ps; };
return 0;
}
class C {};
I just modified the example given here.
Why is that the struct forward declarations work but not the class forward declarations?
Does it have something to do with the namespaces - tag namespace
and typedef namespace
? I know that the structure definitions without typedefs go to tag namespace.
Structures are just classes with all public members. So, I expect them to behave similarly.
Upvotes: 3
Views: 7966
Reputation: 4112
Forward declaration works for classes, but other then you have expected.
First, you have to write class B;
before the code of your main
routine.
Then you have to write B * bb;
instead of B bb;
. You can construct an object of type B only after class definition.
The reason for this behavior is as follows: The compiler does not know how many bytes it has to allocate on the stack for an instance of class B, as this information depends on the definition of the class (which you have not given at that time). A pointer to an instance of class B however can be constructed after a forward declaration of B, since the size of a pointer is previously known (and the normally the same for all pointer types).
Upvotes: 10
Reputation: 72678
Your line:
struct t tt;
Does not compile for me, I get:
.\TestApp.cpp(11) : error C2079: 'tt' uses undefined struct 'main::t'
(This is Visual C++ 2008)
Upvotes: 1
Reputation: 688
I don't think the line "struct t tt;" will compile.
In C++, struct and class are the same except with different default access privileges.
Upvotes: 1
Reputation: 175715
Class forward declarations work fine; you just didn't include one. Add
class B;
above the bb
declaration and it'll work
EDIT: As kibibu pointed out, you can't declare an incomplete type unless it's a pointer, so
B* bb;
would work, but your way wouldn't. Good call
Upvotes: 4