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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With