Initializer list and initializing derived class members

Initializer list in C++ looks like in the example below (see constructor od D class):

class B {
  public:
    B() { } 
};

class D : public B {
  public:
    int x;
    int y;

    D(int _x , int _y) : x(_x) , y(_y +1) { }
};

Now, what if class B had a protected member (z), which you had to initialize in the derived class? It can’t be done in the initializer list. It can be done as below though.

class B {
  public:
    B() { } 
  protected:
    int z;
};

class D : public B {
  public:
    int x;
    int y;

    D(int _x , int _y, int _z) : x(_x) , y(_y +1) { 
        z = _z;
    }
};

Looks simple but if you are switching to C++ after several years it no longer must be so icon_smile-1472364

Update [2011-12-10]
It’s worth remembering that one should always initialize member variables in order they are defined in the class to avoid illegal dependencies that are hard to find.

Previous Post
Next Post