Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular dependencies C++

I'm trying to compile something like the following:

A.h

#include "B.h"
class A {
    B * b;
    void oneMethod();
    void otherMethod();
};

A.cpp

#include "A.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

B.h

#include "A.h"
class B {
    A * a;
    void oneMethod();
    void otherMethod();
};

B.cpp

#include "B.h"       
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}

Until now I haven't had problems using forward declarations, but I can use that now, because i can't use atributtes or methods of only-forward-declarated classes.

How can I solve this?

like image 879
José D. Avatar asked Jun 25 '26 02:06

José D.


2 Answers

In C++, unlike Java and C#, you can define a member function (providing its body) outside the class.

class A;
class B;

class A {
    B * b;
    void oneMethod();
    void otherMethod() {}
};

class B {
    A * a;
    void oneMethod();
    void otherMethod() {}
};

inline void A::oneMethod() { b->otherMethod(); }
inline void B::oneMethod() { a->otherMethod(); }
like image 128
Ben Voigt Avatar answered Jun 26 '26 17:06

Ben Voigt


As long as I'm understanding your question right, all you need to do is this:

A.h

class B;// Forward declaration, the header only needs to know that B exists
class A {
    B * b;
    void oneMethod();
    void otherMethod();
};

A.cpp

#include "A.h"
#include "B.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

B.h

class A;// Forward declaration, the header only needs to know that A exists
class B {
    A * a;
    void oneMethod();
    void otherMethod();
};

B.cpp

#include "B.h" 
#include "A.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency      
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
like image 43
Dan F Avatar answered Jun 26 '26 15:06

Dan F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!