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

前端 未结 2 1149
感动是毒
感动是毒 2021-01-12 12:39

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 poss

相关标签:
2条回答
  • 2021-01-12 13:11

    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) {}
    
    0 讨论(0)
  • 2021-01-12 13:14

    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() {}
    
    0 讨论(0)
提交回复
热议问题