C++: Inheritance

Inheritance allows to reuse the functionality. Inheritance inherits base class members to derived class. We can use base class members within 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.

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; 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 (‘,’).

When you inherit from base class, all of its members will inherit to derived class. Except the following:

  • private members
  • constructors and destructor
  • 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.

Lets take a simple example:

#include <iostream>

using namespace std;

// BaseX
class BaseX
	int bx;

	int by;

	int bz;

		bx = 100;
		by = 200;
		bz = 300;

// DeriveX
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
int main()
	DeriveX dx;

	return 0;

When we run the program the output will be:

by: 200
bz: 300

Observe that BaseX‘s private member “bx” is not accessible in DeriveX.


Leave a Reply