OOP: INHERITANCE
Inheritance and Access Specifiers
Access specifiers decide who can access class members.
The three access specifiers are:
publicprotectedprivate
Inheritance makes this topic more important because a derived class may need to use base-class members.
Basic Access Table
| Member access | Same class | Derived class | Outside object |
|---|---|---|---|
public |
yes | yes | yes |
protected |
yes | yes | no |
private |
yes | no | no |
This table assumes public inheritance.
Complete Example
#include <iostream>
using namespace std;
class Parent {
private:
int privateData = 10;
protected:
int protectedData = 20;
public:
int publicData = 30;
int getPrivateData() const {
return privateData;
}
};
class Child : public Parent {
public:
void show() const {
cout << protectedData << endl;
cout << publicData << endl;
cout << getPrivateData() << endl;
// cout << privateData; // error
}
};
int main() {
Child child;
child.show();
cout << child.publicData << endl;
return 0;
}
Important Private Member Rule
Private members of the base class:
- Exist inside the derived object.
- Are controlled by the base class.
- Cannot be accessed directly by the derived class.
The derived class can use public or protected base methods to work with private base data.
When To Use Protected
Use protected when:
- Derived classes genuinely need direct access.
- Outside code should not access the member.
Do not make everything protected. Too much protected data weakens encapsulation.
Viva Answer
Public members are accessible everywhere, protected members are accessible inside the class and derived classes, and private members are accessible only inside the class itself. In inheritance, base private members exist in the derived object but cannot be accessed directly by the derived class.
Quick Check
- Can a derived class directly access base private members?
- Can outside code access protected members?
- Why should protected data be used carefully?