Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the protected and private member variables in C++ inheritance

I am a newbie to C++, I have a question regarding to the c++ protected and private members in inheritance.

If a class is public inherits a based class, does the protected and private member variable will be part of derived class?

For example:

class Base
{
   protected: 
       int a;
       int b;
   private:
       int c;
       int d;
   public;
       int q;
};

class Derived: public Base
{

};

does class Derived also have all the member of a, b, c, d, q? and can we define a int a as public, protected, and private in Derived class?

like image 745
ratzip Avatar asked Apr 02 '15 08:04

ratzip


People also ask

Are private member variables inherited?

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.

What happens when a protected member is inherited as private?

protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.

What is difference between protected and private access specifiers in inheritance?

The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class. Private member are not inherited in class. Protected member are inherited in class.

Can an inherited class access protected members?

The protected members are inherited by the child classes and can access them as its own members. But we can't access these members using the reference of the parent class. We can access protected members only by using child class reference.


2 Answers

No class can access private variables. Not even subclasses.

Only subclasses can access protected variables.

All classes can access public variables.

like image 91
therainmaker Avatar answered Oct 27 '22 01:10

therainmaker


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.

like image 23
Graham Dawes Avatar answered Oct 27 '22 00:10

Graham Dawes