pkdc
pkdc

Reputation: 173

Using constructor base and member initializer list with inheritance

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

Upvotes: 1

Views: 2539

Answers (2)

user4145096
user4145096

Reputation:

derivedClass::derivedClass(argumentsSetOne, argumentsSetTwo, .....) : baseClassOne(argumentsSetOne) , baseClassTwo(argumentsSetTwo) { }

order doesn't really matter...by that i mean, you can specify argumentsSetTwo before argumentsSetOne in the Derived Class's Constructor's arguments field. But again it should be same as specified in the prototype....

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148900

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;
};

Upvotes: 1

Related Questions