user2701114
user2701114

Reputation: 141

Are Forward Declarations Needed If You Already Have Include Guards?

If you have a set of header files with include guards, is it really necessary to have forward declarations?

I've been doing this out of habit in my code, and I recommended a colleague add forward declarations to their code, but when they asked whether it was really necessary because of the include guards already present, I was at a bit of a loss. It seems like it's good practice, but wouldn't include guards solve all of the problems that forward declarations do?

Here's an example. Suppose I have a header file like so:

//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.
}

If I know that there is an include guard in MyClassA.h, would the above be better practice than the following? And, if so, why?

#include “MyClassA.h”  

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

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

Would the second example also prevent a circular declaration/multiple declaration?

Upvotes: 0

Views: 324

Answers (1)

R Sahu
R Sahu

Reputation: 206577

You are mixing two unrelated concepts.

  1. You use forward declaration when you need something by name only.

  2. You use include guards to prevent processing of the same code multiple times in a single translation unit, i.e. .cpp file. Whether you use include guards or not is based on the intended use of the .h file. Most of the time, you don't want the contents of the file to be processed multiple times in a .cpp file but there are use cases where allowing that is essential. For the later category of uses, you must not use include guards.

You can combine them anyway you want.

It's ok to:

  1. Use forward declarations AND use include guards.
  2. Use forward declarations AND not use include guards.
  3. Not use forward declarations AND use include guards.
  4. Not use forward declarations AND not use include guards.

Upvotes: 1

Related Questions