Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incomplete type named in nested name specifier

Tags:

c++

I was compiling the following code:

class B;

class A {
    A();
    friend A B::newAObject();
};

class B {
    friend A::A();
public:
    A newAObject();
};

This may seem strange, but the idea was to have a class A that could only be produced by an object of type B (who would probably be a singleton).

The problem is that I've created a circular dependency between these objects. A must be defined before B, and B must be defined before A. Apparently forward declaring B is not good enough, B must actually be fully defined before A (and vice versa).

How do I get around this?

Edit: the actual error is: Incomplete type 'B' named in nested name specifier.

Note: there is another post that is similar to this here: Error: incomplete type used in nested name specifier, but it's heavily templatized and that was confusing me, hence this post.

like image 257
Michael Dorst Avatar asked Jul 02 '12 00:07

Michael Dorst


1 Answers

C++2003 states that when the contents of the class are accessed, this class should be fully defined. The forward declaration is not enough. This means that circular dependencies like yours are simply not allowed.

p.s. Declaring the whole class as a friend should work, if this is all what you need.

By the way, friend specification generates forward declaration for the class, look at the following code:

void    F10(C1 &p1); 

class C2 
{ 
    friend class C1; 
}; 

void    F11(C1 **p1);

Compiler will give syntax error for F10 because C1 is undefined, but F11 will compile fine because of the friend spec. This may sound strange but this is defined in the standard and compilers follow this.

like image 127
Kirill Kobelev Avatar answered Nov 20 '22 11:11

Kirill Kobelev