C++ Initialize base class' const int in derived class?

六眼飞鱼酱① 提交于 2019-12-01 16:34:10

Simply call the appropriate Base constructor in the Derived's initialization list:

Derived(const int index, const std::string name) : Base(index), m_name(name) {}

You can call the base constructor like this:

class B1 {
  int b;
public:    
  // inline constructor
  B1(int i) : b(i) {}
};

class B2 {
  int b;
protected:
  B2() {}    
  // noninline constructor
  B2(int i);
};

class D : public B1, public B2 {
  int d1, d2;
public:
  D(int i, int j) : B1(i+1), B2(), d1(i)
  {
    d2 = j;
  }
};

Since c++11 your can even use constructors of the same class. The feature is called delegating constructors.

Derived(){}
Derived(const int index, const std::string name) : Derived() {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!