Why can't a derived class call protected member function in this code?

后端 未结 4 1900
挽巷
挽巷 2020-11-27 15:14
#include 

class Base
{  
protected:
    void somethingProtected()
    {
        std::cout << \"lala\" << std::endl;
    }
};

class Deri         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 15:26

    I believe you have some confusion on how to access base class members. It is only this way:

    class Derived : public Base
    void drivedMethod() {
        Base::baseMethod();
    }
    

    in your example you are trying to access a protected member of another instance.

    a Derived instance will have access to it's own protected members but not to another class instance protected members, this is by design.

    In fact accessing the protected members of another class, from another instance members or from the main function are in fact both under public access...

    http://www.cplusplus.com/doc/tutorial/inheritance/ (look for the access specifier table to see the different levels)

    Both examples prove the same thing for example:

    void somethingDerived(Base& b)
        {
            b.somethingProtected();  // This does not
    

    here your Derived class is getting b as a parameter, so it is getting another instance of base, then because b.somethingProtected is not public it will not complie..

    this will complie:

    void somethingDerived()
    {
       Base::somethingDerived();
    

    your second example complies fine because you are accessing a public method on another d class

    >  void somethingDerived(Base& b)
    >     {
    >         b.somethingProtected();  // This does not
    >     }
    

提交回复
热议问题