As a returning newbie in C ++, I am trying to sort the #include methodology.
I follow a specific set of guides, which I describe in detail below in the following example. So far this has worked for me (the whole project keeps compiling :)), but I'm worried that in the future I may run into problems, so my questions - is this the correct methodology? Is there a better one? What basic logic explains this?
Consider the following example:
Father.h
#pragma once class Father {
ClassA.h
#pragma once #include "Father.h" #include "StructC.h" class ClassB; class ClassA : public Father { StructC struct_c_obj; ClassB class_b_obj;
ClassA.cpp
#include "Father.h" #include "ClassB.h" #include "StructC.h"
ClassB.h and ClassB.cpp
Class does not include
StructC.h
struct StructC {
I follow these recommendations:
- All * .h are headed by
#pragma once - If ClassA inherits from the Father class, it must include it in both * .h and * .cpp files
- If ClassA uses ClassB (and has a ClassB variable declared in the class scope), it has a
class ClassB; declaration of class ClassB; in ClassA.h and #include "ClassB.h" in ClassA.cpp - If ClassA uses StructC (and has a StructC variable declared in the class scope), it must include it in both ClassA.h and ClassA.cpp
- If ClassA uses ClassD or StructE, but only in the ClassA.cpp file, then it should include them only there
This is probably a clumsy set of recommendations with a little understanding of the basic logic, so I'm probably going to get some anger ... Bring it, I'm am trying to find out here ... :)
UPDATE:
- As some of them are written below, I have an error in the example - you can use forward ClassB declaration in ClassA only if ClassA has a pointer or a reference to ClassB, and not if it has a simple ClassB data element.
source share