0

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?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
AlgorithmsX
  • 307
  • 2
  • 10

1 Answers1

1

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.

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • `foo::method` could use a return type as well. – user4581301 Aug 13 '16 at 05:31
  • And he is missing some semicolons at the end of the classes too, I hadn't noticed. Not to mention everything is private ... I think he just wrote a quick demonstrative code in there. – Daniel Aug 13 '16 at 05:35
  • @Mondkin This worked perfectly. Could this also work if bar was a subclass of foo? – AlgorithmsX Aug 13 '16 at 13:51
  • It that case it should also work. Note that certain combinations will not work, as `foo` being a subclass of `bar`, or `foo` having a field of type `bar`, because in those cases the compiler needs to know how much space the objects of the class `bar` will take, and that is information the forward-declaration doesn't give. – Daniel Aug 13 '16 at 22:45