Search code examples
c++compilationincludec-preprocessorheader-files

How to #include inside .cpp file?


In the following example, the FileA header is included in FileB header; Some of the classes in FileB.h are forwardly declared inside FileA.h;

in FileA.h

//Forward Declaration.
class classB;

//Main classes.
class ClassA
{
//...
private:
void MemberFunction(ClassB* PtrToClassBObj);
}

In FileB.h

//Includes.
#include FileA.h

//Main classes.
class ClassB
{
//...
public:
int MemberVariable = 0;
}

Then in FileA.cpp

#include FileA.h

//Member functions definitions.
void ClassA::MemberFunction(ClassB* PtrToClassBObj)
{
if(PtrToClassBObj)
PtrToClassBObj->MemberVariable++;
}

Is that enough to make FileA.cpp capable of accessing public members of said classes from FileB.h? or should FileA.cpp itself include FileB.h? And was the forward declaration needed (assuming no use of the class name inside FileA.h, and only used inside FileA.cpp exclusively)? What is the general best practice advice if any?


Solution

  • Is that enough to make FileA.cpp capable of accessing public members of said classes from FileB.h?

    No, it is not "enough" - the full definition of ClassB needs to be visible.

    or should FileA.cpp itself include FileB.h?

    It should, because it uses the class at PtrToClassBObj->MemberVariable.

    was the forward declaration needed

    As presented, no - you can remove #include FileA.h from FileB and make FileA include FileB.

    (assuming no use of the class name inside FileA.h, and only used inside FileA.cpp exclusively)?

    Assuming there is no use of ClassB inside FileA.h, there is no use for forward declaring ClassB, so the forward declaration is not needed. The assumption conflicts with presented code, as the symbol ClassB is used in ClassA::MemberFunction declaration.

    What is the general best practice advice if any?

    Follow code guidelines. Do not write spaghetti code and do not have circular dependencies. Prefer clear, easy-to-understand, readable code structured in a hierarchical tree. Compile with all warnings enabled, use code linters and sanitizers. Exercise regularly. Eat healthy.