Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive friend 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 error:

prog.cpp:8: error: invalid use of incomplete type ‘struct B’
prog.cpp:1: error: forward declaration of ‘struct B’
like image 216
BCS Avatar asked May 28 '11 00:05

BCS


2 Answers

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

like image 92
Lightness Races in Orbit Avatar answered Oct 19 '22 12:10

Lightness Races in Orbit


According to IBM's documentation (which I realize is not normative):

A 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 grants friendship to all of B's members. And you probably already knew that.

like image 29
Nemo Avatar answered Oct 19 '22 13:10

Nemo