MVTC
MVTC

Reputation: 855

Resolving circular dependency in which each dependent structure accesses it's methods

How should I resolve the following type of circular dependency?

//A.hpp
#include "B.hpp"

struct A {
    B b;
    int foo();
};

//A.cpp
#include "A.hpp"

int A::foo{
    b.fi(*this);
}


//B.hpp
struct A;

struct B {
    int fi(const A &a);
};

//B.cpp
#include "B.hpp"

int B::fi(const A &a){
    if(a.something()) 
        something_else();
}

Upvotes: 5

Views: 117

Answers (3)

Beta
Beta

Reputation: 99144

//B.hpp

struct A;

#ifndef B_H    // <-- header guard
#define B_H

struct B {
    int fi(const A &a);
};

#endif

//B.cpp
#include "A.hpp"   // <-- so that fi() can call A::something()
#include "B.hpp"

int B::fi(const A &a){
    if(a.something()) 
        something_else();
}

Upvotes: 1

Chad
Chad

Reputation: 19052

Forward declare A in B.hpp as you have,, then include A.hpp in B.cpp. That's what forward declarations are for.

Upvotes: 5

perreal
perreal

Reputation: 98088

You can define base classes for A and B, and define fi and something as virtual functions of these bases in separate headers. Then include these headers from both A and B.

Upvotes: 1

Related Questions