I have 3 classes:
ClassA.h
ClassA
{
public:
ClassA();
};
ClassB.h
#include "ClassA.h"
classB
{
public:
ClassB();
private:
ClassA m_classA;
};
ClassC.h
#include "ClassB.h"
ClassC
{
public:
ClassC();
private:
ClassB m_classB;
};
ClassC needs ClassB and ClassB needs ClassA. ClassC doesn’t need ClassA so should I put the #include “ClassA.h” that’s inside the ClassB header inside the source file and make a global object or is there a better way?
ClassB.cpp
#include "ClassB.h"
#include "ClassA.h"
ClassA g_classA;
ClassBhas aClassAobject, so its class declaration needs the full declaration ofClassA. So you need to include theClassA.hheader inClassB.h*, regardless of what happens withClassC.If you want to avoid including headers what you can do is store a (smart) pointer to
classAand forward declare it. Then you only need to includeclassA.hinclassB.cpp. Here is a simple example:in
A.hin
B.hin
B.cpp* Strictly speaking,
ClassA.hcould be included in other files as long as it is indirectly included inClassB.h. But it is better to include what you need where you need it, and not depend on indirect includes.