2011-12-20 CPlusPlus0X

Object construction made easier

There are three things made for easier object construction. Non static members can be initialized in a new consistent way, constructor can delegate construction to other constructors and constructors can be inherited. The last improvement has as of this writing not been implemented in gcc yet so we'll come back to that later. For the other two read below.

Non static member initialization

Before non static members had to be initialized in the constructor. Now they can be initialized directly in the class definition like this:

class Initialized
{
  public:
    Initialized();
    Initialized(const string& initialValue);

  private:
    string initializedMember = "Hey I'm initialized right here!";
}

This is so clear that it is good on its own. Before you had to initialized the member in both of the constructors. This lead often to the need to define a special method just for doing the common construction and the you had to call that one in the body of all constructors. No need for that now. Simply initialize the member in a clear and concise way in the class definition.

Constructor delegation

Similar to the member initialization improvement is constructor delegation. This means that a constructor can delegate the construction to another constructor. So you can keep all the construction code to one constructor and avoid the extra initialization member that way. The syntax is the same as for initialization lists.

class Delegation
{
  public:
    Delegation(const string& initialValue) { <complex initialization code> };
    Delegation() : Delegation("Initial value") { ... };
}

The default constructor of Delegation delegates the construction to the constructor taking a string parameter by calling it in the member initialization list and passing in the value. This way all the nitty and gritty initialization details can be placed in the first constructor.

Note that if delegation is used no member can be initialized in the initialization list. Other assignments will have to wait until the body of the constructor.