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

Enjoy this Post?

Your vote will help me grow this site and provide even more information

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


  1. 1 Tomek

    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.

  2. 2 Jarosław Dobrzański

    Good point!

  3. 3 Frogger

    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




Switch to our mobile site