Why can't I access a protected member from an instance of a derived class?

后端 未结 8 1104
难免孤独
难免孤独 2020-12-01 16:46

I haven\'t done C++ in a while and can\'t figure out why following doesn\'t work:

class A {
protected:
  int num;
};

class B : public A {
};

main () {
  B          


        
相关标签:
8条回答
  • 2020-12-01 17:33

    yes protected members are accessible by derived classes but you are accessing it in the main() function, which is outside the hierarchy. If you declare a method in the class B and access num it will be fine.

    0 讨论(0)
  • 2020-12-01 17:33

    Yes, protected members are accessible by the derived class, but only from within the class.

    example:

    #include <iostream>
    
    class A { 
       protected:
       int num;
    };
    
    class B : public A {    public:
       void printNum(){
          std::cout << num << std::endl;
       }
    
    };
    
    main () {
       B * bclass = new B ();
       bclass->printNum();
    }
    

    will print out the value of num, but num is accessed from within class B. num would have to be declared public to be able to access it as bclass->num.

    0 讨论(0)
提交回复
热议问题