I have a question on how to use initializer list for constructors of a derived class that are inheriting from constructors of a base class.
This is the code that works:
class base {
public:
base():x(0) {}
base(int a):x(a) {}
private:
int x;
};
class derived : public base {
public:
derived():base():y(0) { y=0; }
derived(int a, int b):base(a) { y=b; }
private:
int y;
};
However, I want to use the member initializer list to initialize the variables directly, and this leads to an error:
class base {
public:
base():x(0) {}
base(int a):x(a) {}
private:
int x;
};
class derived : public base {
public:
//derived():base():y(0) {} //wrong
//derived(int a, int b):base(a):y(b) {} //wrong
derived():base(), y(0) {} // corrected
derived(int a, int b): base(a), y(b) {} //corrected
private:
int y;
};
What's the right syntax for constructors that inherits from another constructor to use initializer list?
Thanks :)
As noted by Dieter, you can easily have many initializers in a constructor, they simply must be separated with comma (,
) instead of column (:
).
You class derived should then be :
class derived : public base {
public:
derived():base(),y(0) {}
derived(int a, int b):base(a),y(b) {}
private:
int y;
};