C++: Initialization of inherited field

前端 未结 4 1194
长发绾君心
长发绾君心 2020-12-02 01:36

I\'ve a question about initialization of inherited members in constructor of derived class. Example code:

class A
    {
public:
    int m_int;
    };

class          


        
4条回答
  •  长情又很酷
    2020-12-02 02:01

    In order to construct an instance of class B you first instantiate an instance of class A. During that instantiation m_int gets initialized. It's after that intialization that b's constructor is called, so you can't reinitialize m_int. If that's your goal then you can implement a constructor for A that takes an int and then call that in B's initialization list:

    class A
    {
    public:
      A(int x): m_int(x) {}
      int m_int;
    };
    
    class B: public A
    {
    public:
      B(): A(2) {}
    };
    

提交回复
热议问题