C++: Why does my DerivedClass's constructor not have access to the BaseClass's protected field?

前端 未结 6 984
执笔经年
执笔经年 2020-12-14 06:14

I have a constructor attempting to initialize a field in a base class. The compiler complains. The field is protected, so derived classes should have access.



        
6条回答
  •  攒了一身酷
    2020-12-14 06:42

    In the initializer list you can just set values for attributes of the same class. To access it, you must attribute the value in the body of the constructor:

    DerivedClass::DerivedClass(std::string data) {m_data = data; }

    Or, if it is expensive to copy the object, you pass the m_data as an argument to the parent class constructor :

    DerivedClass::DerivedClass(std::string data) : BaseClass(data) {}

    Tip: Pass your data as a reference to prevent the copy constructor.

    See more info here: order of initialization of C++ constructors.

提交回复
热议问题