Friends recursive classes

Is there any way around this:

class B; class C { public: C() { } private: int i; friend B::B(); }; class B { public: B() { } private: int i; friend C::C(); }; 

Gives an error:

 prog.cpp:8: error: invalid use of incomplete type 'struct B' prog.cpp:1: error: forward declaration of 'struct B' 
+7
source share
4 answers

You just can't do it. Remove the circular dependency.

+5
source

According to IBM documentation (which I understand is not normative):

The class Y must be defined before any member of Y can be declared a friend of another class.

So, I think the answer is no.

Of course you can use

 friend class B; 

... instead of friend B::B() , but that gives friendship to all members of B. And you probably already knew that.

+3
source

Since you are very selective about friendship (access to certain member functions provided by specific classes), the Lawyer-Client Idiom may be what you need. I'm not sure how well this will work with designers.

+2
source

I understand that this is a really stupid idea, but could you theoretically accomplish this by inheriting by creating friend constructors of the parent class? The code is compiled, at least dubious, although it may be.

 class A { public: A() { } private: int i; }; class D { public: D() { } private: int i; }; class B : public A { public: B() { } private: friend D::D(); }; class C : public D { public: C() { } private: friend A::A(); }; 
+1
source

All Articles