Tuesday, July 13, 2010

Forward declaration vs #include directives

Using forward declaration of C++ classes in header files decreases total compilation time of the application and lowers dependencies. This also makes application easier to modify. It is suggested that when it is necessary to use #include directives, use it. But also avoid usage of unnecessary #include directives and replace them with forward declaration in the header file. Some basic rules that I obey most of the time when using #include directives and forward declarations are as follows:
#include directive :
- Use in both .h header file and implementation file
- Base classes are introduced by using include directives

forward declaration :
- Use in .h header file
- Pointer return values and method parameters can be forward declared

Sample.h file :
//include directive for base class
#include "BaseItemEntity.h"
//forward declaration for method parameters and return values
class QString;
class Item;
class ItemBody : public BaseItemEntity
{ 
public:
 QString getItemID();
 Item* getItemByName(QString&);
};

Sample.cpp file :
#include "Sample.h"
#include "Item.h"

QString ItemBody::getItemID()
{
 return QString();
}

Item* ItemBody::getItemByName( QString& name)
{
 Item* item = new Item(name);
 return item;
}


There is also a useful c++ coding guide that is giving clues for header file dependencies at this link

No comments:

Post a Comment