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

有些话、适合烂在心里 提交于 2019-12-01 15:31:15

问题


I have a constant int variable in my base class, and I would like to initialize responding one in my derived class, with different value (taken as a parameter), is this possible?

Here's what I did:

// Base.h (methods implemented in Base.cpp in the actual code)
class Base {
    public:
        Base(const int index) : m_index(index) {}
        int getIndex() const { return m_index; }
    private:
        const int m_index;
};

// Derived.h
class Derived : public Base {
    public:
        Derived(const int index, const std::string name) : m_name(name) {}
        void setName(const std::string name) { m_name = name; }
        std::string getName() const { return m_name; }
    private:
        std::string m_name;
};

But obviously it's asking me for Base::Base() which doesn't exist, and if I define it, I will have to give default value for m_index, which I don't want to do. Do I have to define const int m_index separately in every derived class?

Similiar question, but I'm not sure if the static affects this in any way: C++ : Initializing base class constant static variable with different value in derived class?


回答1:


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) {}



回答2:


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() {}


来源:https://stackoverflow.com/questions/13591886/c-initialize-base-class-const-int-in-derived-class

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