home > resources > c++ coding standard > online version

Uses Of The Constructor

Only initialize member variables

The constructor should only initialize the member variables and preferably not through assignment. Also, explicitely initialize all member variables even if you're just calling their default constructor. It's better to be clear from the beginning than in doubt later.

Delegate all logic

No real action should be done in the constructor, delegate everything to a seperate initialize() method. This will allow multiple constructors to use the shared code logic in the initialize method by passing the appropriate arguments.

Call the parent's constructor explicitely

If the class has been derived from another class, the constructor has to call the appropriate parent's constructor explicitely. Don't rely on the implicite calling of the default constructor since it makes code unclear. It's much better to clearly state that the use of the parent's default constructor has been examined by you and that you think it's the best course of action.

Example 5-1. Uses Of The Constructor Example

class Child : public Parent
{
public:
    Child() :
        Parent(),
        mAge(),
        mName("unknown")
    {
        initialize();
    }
          
    void initialize()
    {
        /* do the real work */
    }
          
private:
    int       mAge;
    QString   mName;
}