Why incomplete type (forward declared) size calculation cannot be postponed when using type as a field?

Viewed 90

In the following code:

class B;

struct A
{
   B* b; // <- why MUST be a pointer? Why size cannot be calculated later...?
}

struct B
{
   ...
}

As far as I understand, struct A must define b as B*, as the compiler cannot tell the size of B when calculating size of A.

What I do not understand, is why the compiler cannot postpone the calculation until it does find the full definition of B (as it was promised by the programmer by forwarding declare the class)

2 Answers

Imagine that you could actually define A as:

class B;

struct A {
   B b; // not a pointer
}

That is, b is a data member of incomplete type – the compiler doesn't know the size of B at this point.

Then, if B were defined as:

struct B {
   A a;
}

This would require infinite memory.

The reason is simply that C++ is designed to be compiled in a single pass through the source code (more or less); the goal is that the compiler doesn't have to postpone compiling something because there's not enough information at the point where it's defined.

Related