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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With