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 Initializer list and initializing derived class members

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.

3 Responses to “Initializer list and initializing derived class members”


  • You could create another constructor in B that accepts _z and then call that constructor in your derived class D:

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

    I didn’t try compiling it though.
    Anyway, initialization lists provide better performance only for bigger objects. And it is worth to remember that members are always initialized in the order in which they are declared in the class definition.

  • Thank you!!
    I’m a learner and I needed to know. I used to learn slow but now i’m just blazing it’s great! I’m excited for life!!!
    Also thanks Tomek for that I understood it actually which is great IT MEANS I’M LEARNING!!! yes :) :) :)
    All smiles!

    Thanks again random google person, i’m favoriting your site thing. :)

Leave a Reply