C++: Initializing parent class member variables in derived class constructor

Usually we initialize member variables in constructor using initialization list.

class Base {
public:
    int i;
    explicit Base(int _i) : i(_i) {
        //other initialization code
    }
};

But we cannot initialize the parent class public or protected member variable in derived class constructor’s initialization list.

class Derived: public Base {
public:
  int j;
  Derived(int _i, int _j) : i(_i), j(_j) {

  }
};

The above code will produce the following error:

par_var_init.cpp: In constructor ‘Derived::Derived(int, int)’:
par_var_init.cpp:16:28: error: class ‘Derived’ does not have any field named ‘i’
Derived(int _i, int _j) : i(_i), j(_j) {

Using parent constructor

The correct way to do this is by calling the base class constructor to initialize its variables.

class Derived: public Base {
public:
  int j;
  Derived(int _i, int _j) : Base(i), j(_j) {

  }
};

Initializing parent’s member variables in derived class constructor’s body

It is possible to initialize parent’s member variables in derived constructor’s body.

class Derived: public Base {
public:
  int j;
  Derived(int _i, int _j) : j(_j) {
    i = _i;
  }
};

Note: the following approach is wrong!

class Derived: public Base {
public:
  int i;
  int j;
  Derived(int _i, int _j) : i(_i), j(_j) {
  }
};

This will create a new variable in derived class called i that is separate from Base::i.