How to use Forward Declaration in C++

Imagine that you have two classes: MyClassA and MyClassB. Both of these classes have their respective .h and .cpp file. Imagine you need to reference MyClassA in MyClassB, do you know where you should use

#include "MyClassA.h"

and where to use

class MyClassA

in the files of MyClassB?

For example, the code below shows that I'm using

#include "MyClassA.h"

in both header and implementation files of MyClassB:

//This is the header file: MyClassB.h
#include "MyClassA.h" //Including file for MyClassA    

class B{
    public:
        B(){}
        ~B(){};
        //...
}

//This is the implementation file: MyClassB.cpp

#include "MyClassA.h" //Again, including file for MyClassA

//B's methods implementations goes here...

The question is, is this correct?

Simple answer: The implementation file (.cpp) of MyClassB will always need:

#include "MyClassA.h"

However, the header file (.h) of MyClassB does not necessarily need

#include "MyClassA.h"

For example, in the above example, you can replace #include with a forward declaration:

class MyClassA;  //This is a Forward Declaration 

For example:

//This is the header file of class B
class MyClassA; //This is forward declaration   

class B{
    public:
        B(){}
        ~B(){};
        //...
    }

The question is when do you use

#include "MyClassA.h"

vs.

class MyClassA;

I am not a C++ expert, but these are the tips I always keep in mind:

If you are going to invoke the constructor, copy constructor or any method of MyClassA in the header file of MyClassB, then you need to use #include "MyClassA.h".

This is because the compiler needs to know how to create the object or methods belonging to MyClassA. For example:

//This is the header file of class B
#include "MyClassA.h" //Including file for MyClassA    

class B{
    private:
        MyClassA myClass; //You are invoking a constructor of MyClassA

    public:
        B(){}
        ~B(){};

        inline void print(MyClassA myClass){ myClass->print();}; //You are invoking a copy constructor and a method of MyClassA
}

However,

if you have a pointer to MyClassA in MyClassB.h or passing MyClassA by reference in a method argurment, you can simply use the forward declaration instead.

For example:

//This is the header file of class B
class MyClassA; //This is forward declaration    

  class B{
      private:
          MyClassA *myClass; //pointer to MyClassA
      public:
        B(){}
        ~B(){};

        void print(MyClassA* myClass); //Passing by reference. Not calling any methods of MyClassA.
}

So, there you have it. Use #include "MyClassA.h" in the header file of MyClassB.h whenever you will be invoking the constructor or any method of MyClassA. If you are not, you can simply use a forward declaration in the header file of MyClassB.h.

PS. Sign up to my newsletter and get development tips

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.