Samuel Ng Samuel Ng - 2 months ago 7
C++ Question

Circular Dependencies between C++ classes

I've read in this question that


If you really have a model where A contains B and B contains A then these classes appear to be incapable of living without each other. In which case perhaps you only really have one class and not two.


What would the case be if A may contain B, but B should always have a reference to A (B cannot exist without A)?

To illustrate, heres a Cube class that may contain a object of Collider class (IE: other cubes with colliders should collide with it).

class Cube
{
public:
Cube();
~Cube();

Collider collider; //Optional Collider
}

class Collider
{
public:
Collider(Cube & parentReference) : parent(parentReference) {}

private:
Cube & parent;
}


In a case such as this, where Cube and Collider should really be two seperate classes, how does one avoid circular dependencies while still be able to store a reference to Cube in Collider?

Edit: This question has since been answered. However, is anyone kind enough to let me know why this question was downvoted, such that I would change how I ask in the future? Duplicate? Not enough info? Too much of a beginner question? Do let me know :)

Answer
class Collider;

class Cube
{
public:
    Collider* collider; //Optional Collider
}

class Collider
{
public:
    Collider(Cube & parentReference) : parent(parentReference) {}

private:
    Cube & parent;
}

Declare the existance of Collider and define it later. C(++) allows pointers to incomplete types. Here's more info about forward declaration.

Comments