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

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

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

class Deri         


        
4条回答
  •  粉色の甜心
    2020-11-27 15:32

    What you have done is illegal in C++. A protected member can not be accessed by an object of a class. Only member functions can access protected members. protected members behave just like private members except while inherited by a derived class. Consider the program given below to understand the difference between private, public and protected members.

    class Base
    {
        private:
        void somethingPrivate()
        {
            std::cout << "sasa" << std::endl;
        }
        public:
        void somethingPublic()
        {
            std::cout << "haha" << std::endl;
        }
        protected:
        void somethingProtected()
        {
            std::cout << "lala" << std::endl;
        }
    };
    
    class Derived : public Base
    {
    public:
        void somethingDerived()
        {
           Base b;
           b.somethingPublic();   // Works fine.
           somethingProtected();  // This is also fine because accessed by member function.
           //b.somethingProtected();  // Error. Called using object b.
           //somethingPrivate();      // Error. The function is not inherited by Derived.
        }
    };
    

提交回复
热议问题