Incomplete type specified in nested name pointer

I compiled the following code:

class B; class A { A(); friend AB::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 created by an object of type B (which would probably be single).

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

How do I get around this?

Edit: actual error: Incomplete type "B" specified in the nested qualifier.

Note: there is another message similar to this here: Error: incomplete type used in the naming specifier , but it is strongly templatized, and this was confusing to me, therefore this post.

+6
source share
1 answer

C ++ 2003 states that when accessing the contents of a class, this class must be fully defined. Preliminary declaration is not enough. This means that circular dependencies like yours are simply not allowed.

ps Declaring an entire class as a friend should work if that's all you need.

By the way, a friend spec generates a front declaration for the class, look at the following code:

 void F10(C1 &p1); class C2 { friend class C1; }; void F11(C1 **p1); 

The compiler will throw a syntax error for F10 because C1 is undefined, but F11 will compile due to a friend specification. This may seem strange, but it is defined in the standard, and compilers follow this example.

+5
source

Source: https://habr.com/ru/post/919462/


All Articles