views:

123

answers:

4
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.

+4  A: 

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

Michael Mrozek
You can't declare a variable of a forward declared class though, can you? (pointers excluded)
kibibu
+1  A: 

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.

JQ
+1  A: 

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)

Dean Harding
+1  A: 

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).

swegi
@swegi: thanks!
Lazer