Also, as a general rule of thumb, I would recommend using forward declarations in your header files. By doing so, you don’t have to include a lot of headers, which can otherwise cause a significant increase in dependencies, leading to slower build times and potential circular dependencies. Forward declarations help to keep the compilation units more independent, ultimately resulting in a more efficient build process.
Here is a simplified way to use forward declaration:
// MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
// Forward declaration of the `OtherClass` class
class OtherClass;
class MyClass {
public:
MyClass();
void doSomething();
private:
OtherClass* otherClassInstance; // Pointer to OtherClass
};
#endif // MYCLASS_H
// MyClass.cpp
#include "MyClass.h"
#include "OtherClass.h" // Include the full definition of OtherClass here
MyClass::MyClass() : otherClassInstance(nullptr) {}
void MyClass::doSomething() {
// Now we have access to OtherClass' methods through the pointer
if (otherClassInstance) {
// Perform operations using otherClassInstance
}
}