What Is an Example of Private Inheritance in C++?
Learn how private inheritance in C++ works with an example and understand its use in restricting base class access.
0 views
Private inheritance occurs in C++ when a class inherits from another class but restricts access to the base class's public and protected members. For example: `class Derived : private Base { ... };` In this case, members of `Base` become private in `Derived`, making them inaccessible from outside the `Derived` class. This is useful when you want to reuse the implementation of the base class without exposing its interface to users of the derived class.
FAQs & Answers
- What is private inheritance in C++? Private inheritance in C++ means a derived class inherits from a base class, but the base class's public and protected members become private within the derived class, preventing outside access.
- How does private inheritance differ from public inheritance? Unlike public inheritance where the base class interface is accessible, private inheritance hides the base class members from users of the derived class, allowing reuse without exposing the base class interface.
- When should I use private inheritance in C++? Use private inheritance when you want to reuse the implementation of a base class but do not want to expose its interface or relationship to users of the derived class.