Derived class cannot access the protected member of the base class

  • A+

Consider the following example

class base { protected :     int x = 5;     int(base::*g); }; class derived :public base {     void declare_value();     derived(); }; void derived:: declare_value() {     g = &base::x; } derived::derived()     :base() {} 

As per knowledge only friends and derived classes of the base class can access the protected members of the base class but in the above example I get the following error "Error C2248 'base::x': cannot access protected member declared in class " but when I add the following line

friend class derived; 

declaring it as friend , I can access the members of the base class , did I do some basic mistake in the declaring the derived class ?


The derived class could access the protected members of base class only through the context of the derived class. On the other word, the derived class can't access protected members through the base class.

When a pointer to a protected member is formed, it must use a derived class in its declaration:

struct Base {  protected:     int i; };  struct Derived : Base {     void f()     { //      int Base::* ptr = &Base::i;    // error: must name using Derived         int Base::* ptr = &Derived::i; // okay     } }; 

You can change

g = &base::x; 


g = &derived::x; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: