Pavlo
Pavlo

Reputation: 1654

Why "incomplete type error" in C++ do not hold for nested classes

I have the following code

class A;
class B;

class A
{
    B b() const { return B();}    
};

class B
{   
    A a() const { return A(); }    
};

it produces the following error:

 In member function 'B A::b() const':
error: return type 'class B' is incomplete
error: invalid use of incomplete type 'class B'
error: forward declaration of 'class B'

But if I put this code inside another class definition like so:

class C
{
class A;
class B;

class A
{
    B b() const { return B();}    
};

class B
{   
    A a() const { return A(); }    
};
};

Compiler do not complain anymore.

Question: why it is ok in second case but wrong in first?

Upvotes: 1

Views: 179

Answers (1)

For the same reason a member function may access a variable declared bellow it in the class body. From the standard, emphasis mine:

6 A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

So inside A::b, the full class definition of C is a given. And that includes the full class definition of B, so you may create an object of that type.

Upvotes: 2

Related Questions