As a returning newbie to C++, I'm trying to sort the #include methodology.
I'm following a certain set of guidelines I detail below the following example. So far this has worked out for me (the entire project keeps compiling :) ), but I'm worried I may encounter problems in the future, therefore my questions are - is this a correct methodology? Is there a better one? What's the underlying logic that explains it?
Consider the following example:
Father.h
#pragma once
class Father
{
// Some implementation
};
ClassA.h
#pragma once
#include "Father.h"
#include "StructC.h"
class ClassB;
class ClassA : public Father
{
StructC struct_c_obj;
ClassB class_b_obj;
// Some implementation
};
ClassA.cpp
#include "Father.h"
#include "ClassB.h"
#include "StructC.h"
// Some implementation
ClassB.h and ClassB.cpp
A class without includes
StructC.h
struct StructC {
// Some implementation
};
I follow these guidelines:
#pragma once
declarationclass ClassB;
decleration in ClassA.h and an #include "ClassB.h"
in ClassA.cppThis is probably a clumsy set of guidelines with little understanding of the underlying logic, so I'm probably going to get some wrath... Bring it on, I am trying to learn here... :)
UPDATES:
These are the guidelines I personally follow :
ClassA
contains a ClassB
so a #include "ClassB.h"
is required. Had the ClassB
type only appear in the file by pointer or reference, a forward reference would have been sufficientClassA.h
first in ClassA.cpp
, and use an arbitrary ordering for the following includes (I'm using alphabetical sort)Regarding other aspects :
#pragma
is non standard, prefer include guards
std::string
appears in your header file, you have to #include <string>
Don't use forward declaration of ClassB, when ClassA has a data member of this type. It's OK to use it, when it has a pointers to ClassB, as in:
#pragma once
#include "Father.h"
#include "StructC.h"
class ClassB;
class ClassA : public Father
{
StructC struct_c_obj;
ClassB *class_b_obj;
// Some implementation
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With