Lux
Lux

Reputation: 33

Resolve circular include of 3 classes in C++

I have 3 classes which I am going to refer to as A, B and C (names in this example are arbitrary). All 3 of these classes consist of a header-file and a cpp-file each.

I have the following dependencies:

I have tried out several options already (include this header here, forward-declaration of class there), but compilation was never succesful. I also couldn't extract any helpful information from answers to problems which solved circular inclusion problems between only 2 classes.

EDIT: Here a minimal (and hopefully sufficient) example of my current setup:
A.h

class A {
private:
    B myB;
};

B.h

class B {
private:
    A* myA;
    C myC;
};

C.h

class C {
private:
    A* myA;
}

I should perhaps also note that B::myA and C::myA are always going to point to the same A-instance.

Upvotes: 2

Views: 121

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

As class C only includes a pointer to class A, it doesn't need the full definition for either A or B (which it doesn't use); so, just a statement declaring A as a class will suffice:

C.h

class A; // Declare that A is a class - then we can have a pointer to it...
class C {
private:
    A* myA;
}

Class B needs the definition of C, because it includes an instance of C; and, like class C, simply declaring A as a class (as is done already in C.h) will do:

B.h

#include "C.h" // Note: This header already declares "A" as a class!
class B {
private:
    A* myA;
    C myC;
};

Class A needs the definition of B, as it contains an instance of B. But note that B.h already includes C.h:

A.h

#include "B.h"
class A {
private:
    B myB;
};

Note that any other files that use one or more of A, B and C need only include the A.h header, as this will itself include the others.

Upvotes: 1

Related Questions