Friday, February 23, 2007

C++ - Forward Declarations

If a class declaration (in a header file) does not need to know the size of any included classes/structs (i.e., the class declaration does not need to contain an actual instantiation of another class or access member data or functions of another class), forward declare the dependent classes/structs to minimize dependencies.

In other words, use pointers and references of classes/structs with respective forward declarations instead of member objects instantiations and #include's. Then, #include dependent files to access the other classes' members and functions in the source file (.c,.cpp). Remember to delete the pointers in the destructor if the class owns the pointer.

In myClass.h:
//Forward declarations
class OtherClass; // defined in otherClass.h
struct OtherStruct; // defined in otherStruct.h

class MyClass
{
private:
OtherClass *mMyOtherClass; //pointer
OtherStruct &mMyOtherStruct; //reference
public:
MyClass(OtherStruct &_struct);
~MyClass();
};

In myClass.cpp
#include "myClass.h"
// include headers of forward declarations
#include "otherClass.h"
#include "otherStruct.h"

MyClass::MyClass(OtherStruct &_struct)
: mMyOtherClass(new MyOtherClass),
// references can only be initialized in
// constructor initialization list
mMyOtherStruct(_struct)
{
// Empty constructor body
}

MyClass::~MyClass()
{
delete mMyOtherClass;
}

No comments: