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
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).
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.
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.
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.
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.
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
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