Search code examples
c++forward-declaration

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


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)


Solution

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