简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM