Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting private members in C++

Tags:

suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private data members

like image 888
shreyasva Avatar asked Apr 20 '10 15:04

shreyasva


People also ask

Can you inherit private members?

Private members are accessible only within the class in which they are declared. So even if you inherit the class, you will have access only to the public and protected members of the base class but private members are not inherited(accessible).

How can private members access inheritance?

You need to define it as protected . Protected members are inherited to child classes but are not accessible from the outside world. after inheriting protected members, you can provide public access. then we should avoid to keep personal data in protected access specifier.

Does a derived class inherit private members?

The derived class doesn't "inherit" the private members of the base class in any way - it can't access them, so it doesn't "inherit" them.

Can we inherit private members in C++?

public, protected and private inheritance in C++ 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.


2 Answers

A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.

like image 124
Avi Avatar answered Oct 14 '22 16:10

Avi


It depends on the inheritance type. If you inherit privately, then the derived class does NOT have access to the Base's private members.

Access                      public     protected    private ----------------------------------------------------------- members of the same class      yes           yes        yes members of derived classes     yes           yes         no not members                    yes            no         no 
like image 40
JRL Avatar answered Oct 14 '22 17:10

JRL