Inheritance allows to reuse the functionality. Inheritance inherits base class members to it’s derived class. We can use base class members within the derived class without rewriting base class code.
C++ allows single inheritance as well as multiple inheritance. In single inheritance, derived class is inherited from a single base class. In multiple inheritance, 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 derived class and out side world. BaseClassName1 to BaseClassNameN are name of the base classes. At least one base class name is required for inheritance. Multiple base class names are separated by comma (‘,’).
What members C++ inheritance inherits to the extended class?
When we are using inheritance means, we are extending the C++ class. When we inherit from base class, all of it’s 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 base class as public members of derived class; and protected members of base class as protected members of derived class.
In protected inheritance, all public members and protected members of base class will becomes protected members of derived class.
All public and protected members of base class will become private members of derived class in private inheritance.
Complete code example
Let’s take a simple example:
using namespace std;
bx = 100;
by = 200;
bz = 300;
class DeriveX : protected BaseX
// -- 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
Run the program and the output is:
Observe that BaseX‘s private member “bx” is not accessible in DeriveX.