C++ friend class circular include

Viewed 136

I have this problem:

I have class A which is friend with class B. The class A has a vector<B>. But I would like for the class B to be able to access the class A.

class A
{
   friend class B;
   static vector<B*> buffer;
}

Class B
{
public:
   B()
   {
      A::buffer.push_back(this);
   }
}

Is there some other way how I could automatically add the class B to the vector?

Thanks for any kind of help!

1 Answers

Your code is almost working.

  • You need to forward declare B
  • You need to use A::buffer.push_back(this);
class B; // forward declaration

class A {
   friend class B;
public:
   static std::vector<B*> buffer;
};

std::vector<B*> A::buffer{};

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

B::B() { A::buffer.push_back(this); }
Related