the protected and private member variables in C++ inheritance

No class can access private variables. Not even subclasses.

Only subclasses can access protected variables.

All classes can access public variables.


All the member of the base class are part of the derived class. However, the derived class can only access members that are public or protected.

Declaring a member of the same name as a member of a Base class "shadows" the member of the Base class. That is the Derived class has its own independent variable that happens to have the same name as the base class version.

This is a personal choice, but I find using variables to communicate between base classes and derived classes leads to messier code so I tend to either make member variables private or use the PIMPL pattern.


The private members of a class can be inherited but cannot be accessed directly by its derived classes. They can be accessed using public or protected methods of the base class.

The inheritance mode specifies how the protected and public data members are accessible by the derived classes.

If the derived class inherits the base class in private mode,

  1. protected members of base class are private members of derived class.
  2. public data members of base class are private members of derived class.

If the derived class inherits the base class in protected mode,

  1. protected members of base class are protected members of derived class.
  2. public data members of base class are protected members of derived class.

If the derived class inherits the base class in public mode,

  1. protected members of base class are protected members of derived class.
  2. public data members of base class are public members of derived class.

Refer this link for more clarification: http://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm


class A  
{ 
public: 
    int x; 
protected: 
    int y; 
private: 
    int z; 
}; 
  
class B : public A 
{ 
    // x is public 
    // y is protected 
    // z is not accessible from B 
}; 
  
class C : protected A 
{ 
    // x is protected 
    // y is protected 
    // z is not accessible from C 
}; 
  
class D : private A    // 'private' is default for classes 
{ 
    // x is private 
    // y is private 
    // z is not accessible from D 
}; 

The below table summarizes the above three modes and shows the access specifier of the members of base class in the sub class when derived in public, protected and private modes:

https://imgur.com/a/yaQjFOJ

https://www.geeksforgeeks.org/inheritance-in-c/