Search code examples
c++classc++11circular-dependencyquaternions

Avoiding Circular Dependencies in Class Definitions in C++


I currently have two classes: foo and bar. Foo uses instances of bar in one of its methods, and bar uses an instance of foo in its constructor. However, this will not compile. I understand that there is a circular dependence, so I tried to break out of this by forward declaring bar inside of foo before the foo's method is declared in the header file. That failed because I cannot actually use bar or any of its components at all in foo's method in the source file. I then tried rearranging it so that everything in the source file that bar needed was already defined, then I put in all the definitions for bar, then I defined the method in foo that uses bar. That failed for the same reason. Here is a simplified version of my code so far:

// Header.h
class foo{
    class bar;

    void method(bar& b);
};

class bar{
    bar(foo& f, double d); 
};

// Source.cpp
#include Header.h
// stuff defining foo that I need for bar in the form foo::foo(...){...}

// stuff defining bar that I need for foo::method

void foo::method(bar& b){
    // do stuff with foo and b
}

I would like to point out that when I remove references to the instance of bar in the definition of foo::method, the code compiles and runs properly.

My specific example has the foo class as a vector in homogenous coordinates and the bar class as a quaternion. The quaternion class uses a vector and an angle of rotation in its constructor, and the vector class uses the quaternion in its rotation method.

Is there a way to code this without removing the dependencies or should I just remove one of the dependencies?


Solution

  • Try forward declaring bar outside of foo:

    class bar;
    
    class foo{
        method(bar& b);
    }
    
    class bar{
        bar(foo& f, double d); 
    }
    

    As you had it there you were forward-declaring a class called foo::bar.