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
 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

Friday, July 9, 2010

static const QString

Java allows to define constant Strings as
public final static String SIZE = "size";
in your .java files.

To define static const QString members for a class in c++ environment,
put your static const QString member into related .h file.
class QString;
class Constants{
 static const QString xmlBaseFolderPath;

Add related initialization of the static member into .cpp file.
#include "Constants.h"
#include <QString>
const QString Constants::xmlBaseFolderPath = "C:\\XML";