Behrouz.M
Behrouz.M

Reputation: 3573

How to define two depend classes?

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

Upvotes: 0

Views: 138

Answers (5)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

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.

Upvotes: 2

Maz
Maz

Reputation: 3375

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:

Upvotes: 1

shreyasva
shreyasva

Reputation: 13456

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

Upvotes: -1

Matteo Italia
Matteo Italia

Reputation: 126827

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

Upvotes: 2

flownt
flownt

Reputation: 760

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.

Upvotes: 2

Related Questions