Junior — Middle
Could you explain the concept of private inheritance in object-oriented programming?
sobes.tech AI
Answer from AI
Private inheritance is a mechanism in C++ where all public and protected members of the base class become private members of the derived class.
This means that:
- External code cannot access base class members through an object of the derived class.
- The derived class can use base class members internally but does not expose them in its interface.
Example:
class Base {
public:
void publicMethod() {}
protected:
void protectedMethod() {}
};
class Derived : private Base {
public:
void useBase() {
publicMethod(); // accessible within the class
protectedMethod(); // accessible within the class
}
};
int main() {
Derived d;
// d.publicMethod(); // error: publicMethod became private in Derived
d.useBase(); // OK
}
Private inheritance is used when you want to implement the functionality of the base class inside the derived class but do not want to expose it as part of the derived class's interface. This differs from public inheritance, where the base class's interface becomes part of the derived class's interface.