Inheritance allows reusing the functionality. Inheritance inherits base class members to its derived class. We can use base class members within the derived class without rewriting the base class code.
C++ allows single inheritance as well as multiple inheritances. In single inheritance, the derived class is inherited from a single base class. In multiple inheritances, the derived class is derived from multiple base classes.
Syntax – Inheritance in C++
Following is the inheritance syntax:
class DerivedClassName : <access specifier> BaseClassName1 [, <access specifier> BaseClassName2, ... , <access specifier> BaseClassNameN]
Here DerivedClassName is the name of the derived class. <access specifier> isĀ either public, protected, or private; which decides the visibility of base class members in the derived class and the outside world. BaseClassName1 to BaseClassNameN are the names of the base classes. At least one base class name is required for inheritance. Multiple base class names are separated by a comma (‘,’).
What members of C++ inheritance inherit the extended class?
When we are using inheritance means, we are extending the C++ class. When we inherit from a base class, all of its members will inherit to derived class. Except the following:
- private members
- constructors and destructors
- some overloading operators (eg: operator=)
public inheritance keeps all public members of the base class as public members of the derived class, and protected members of the base class as protected members of the derived class.
In protected inheritance, all public members and protected members of the base class will become protected members of the derived class.
All public and protected members of the base class will become private members of the derived class in private inheritance.
Complete code example
Let’s take a simple example:
#include <iostream> using namespace std; // BaseX // class BaseX { private: int bx; protected: int by; public: int bz; BaseX() { bx = 100; by = 200; bz = 300; } }; // DeriveX // class DeriveX : protected BaseX { public: DeriveX() { // -- This line will through an error. Because BaseX's private members are not accessible from DeriveX // cout << "bx: " << bx << endl; cout << "by: " << by << endl; cout << "bz: " << bz << endl; } }; // -- main function // int main() { DeriveX dx; return 0; }
Run the program and the output is:
by: 200 bz: 300
Observe that BaseX‘s private member “bx” is not accessible in DeriveX.
**