user0175554
user0175554

Reputation: 53

Complex Circular Dependency among classes

I have 5 classes (A,B,C,D,E), each of which will have their own class and header files.

class A{};
class B
{
  B(A&a);
};
class C
{
  C(B&b);
};
class D:public A
{};
class E:public D
{
   vector<C*> vc;
};

Forward declaration will not work because I also have a lot of sharepointers being used in each of those classes.

Upvotes: 2

Views: 99

Answers (2)

user2249683
user2249683

Reputation:

Each class can declare a destructor and define that destructor in a source including the header for the appropriate type destructed by unique/shared pointer. Than a simple forward of that type in the header will do it.

#include <memory>

// header B
struct A;
struct B {
    ~B();
    std::shared_ptr<A> a;
};

// header A
struct A {};

// source B
#include "a"
#include "b"
B::~B() {}

Upvotes: 0

tohava
tohava

Reputation: 5412

You can use forward declarations for shared pointers as well, you just need to forward declare a destructor function object as well.

Header:

struct A;
shared_ptr<A> create_A();

Impl:

struct A { ... };
struct A_destroyer { void operator()(A *p) { delete p; }  };
shared_ptr<A> create_A() { return shared_ptr<A>(new A(), A_destroyer()); }

Upvotes: 4

Related Questions