James Moore
James Moore

Reputation: 447

Include Class in Source File Rather Than Header

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;

Upvotes: 0

Views: 796

Answers (1)

juanchopanza
juanchopanza

Reputation: 227400

ClassB has a ClassA object, so its class declaration needs the full declaration of ClassA. So you need to include the ClassA.h header in ClassB.h*, regardless of what happens with ClassC.

If you want to avoid including headers what you can do is store a (smart) pointer to classA and forward declare it. Then you only need to include classA.h in classB.cpp. Here is a simple example:

in A.h

class A {};

in B.h

#include <unique_ptr>

class A; // forward declaration of A

class B {
 public:
  B();
 private:
  std::unique_ptr<A> a_; // C++11 smart pointer expressing unique ownership
};

in B.cpp

#include "B.h"
#include "A.h" // we need the full declaration here.

B::B() : a_(new A()) {}

* Strictly speaking, ClassA.h could be included in other files as long as it is indirectly included in ClassB.h. But it is better to include what you need where you need it, and not depend on indirect includes.

Upvotes: 3

Related Questions