tags:

views:

52

answers:

5

take a look at following simple code :

class A;
class B
{
    A a;
};

class A
{
    B b;
};

int main(int argc, char *argv[])
{
    return 1;
}

it does not compile, why ?

Error Message from GCC (Qt): main.cpp:6: error: field ‘a’ has incomplete type

+2  A: 

well that's impossible since A would contain a B which would contain an A etc. if they depend on eachother they could hold references or pointers to eachother or one could hold the other whilst the other holded a pointer/reference.

flownt
thanks a lot ..
Behrouz Mohamadi
you're welcome.
flownt
+2  A: 

IIRC, if you define an object of some kind, it must be a complete type, otherwise its size wouldn't be known and the layout of the struct which would contain it couldn't be known.

Moreover the thing you wrote makes no sense, because if you wanted to create an object of type A, it would include an object of type B, which would contain an object of type A, and so on. Thus, an object of type A or of type B would take infinite space in memory, which is definitely not good.

Instead, if those members were pointers/references the forward declarations would suffice and you wouldn't even have this "little" problem of requiring infinite memory for a structure. :)

Matteo Italia
A: 

you cannot have A a. You have forward declared A, you cannot use it until you define it.

+1  A: 

You must make at least one of them a pointer. Otherwise, you are asking each instance to allocate an instance of the other class. In other words, you are asking it to allocate an infinte amount of memory:

Maz
+2  A: 

In order for the compiler to be able to build class B it needs to know the size of all its members. Forward declaration class A; does not tell that, only introduces the name A into the scope. You can use a pointer or a reference to A, the size of which compiler always knows.

Nikolai N Fetissov