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

前端 未结 6 996
执笔经年
执笔经年 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:58

    Your derived class constructor does have access, but you cannot assign to it in the initialisation list. Change the constructor to:

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

    Alternatively, if no suitable base class constructor is available and you cant add one you can change the constructor to:

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

提交回复
热议问题