ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Types of inheritance in c++ with example program

Updated on June 13, 2016

1. Introduction

In this hub, we will see about Inheritance in C++ with Simple example Program. Inheritance is code re-use mechanism. Consider Truck and Car. They both have the functionality of Accelerate, Brake, starting and stopping the engine. They both have properties like fuel level, current speed etc. But, most of the cars have 4 tires and truck may have six, eight or even 16 make you think that Number tires property may not be same for Truck and car.

From the above discussion of real world object, you can place CVehicle as base class which includes common properties like Fuel Level and Current speed. Similarly, the common action it can perform like Accelerate and Brake can be placed in CVehicle. CCar and CTruck can derive from the CVehicle and these classes have properties and behavior specific to it. Say for example both CCar and CTruck can have member variable to hold Number of tires.

Have a Look at below picture:

Inheritance Model
Inheritance Model | Source

2. The CVehicle Class

The code for the CVehicle class is shown below. This class has two private members m_FuelLevel and m_CurrentSpeed. These two members are accessed in the class member functions Accelerate() and Brake(). In these functions, we modify the member variable m_CurrentSpeed and also display the state of the vehicle in terms of Speed and Fuel level. OK. This is basic functionality that is implemented in the BASE class CVehicle.

class CVehicle
{
protected:
	int m_FuelLevel;
	int m_CurrentSpeed;

protected:
	void PrintVehicleProps()
	{
		cout<< "Base Properties:" << endl;
		cout<< "========================" << endl;
		cout<< "Current Speed:" << m_CurrentSpeed << endl;
		cout<< "Fuel Level:" << m_FuelLevel << endl;
		cout<< endl; 
	}

public:
	//Constructor
	CVehicle()
	{
		m_FuelLevel = 50;
		m_CurrentSpeed = 0;
	}

	//Increase Speed
	void Accelerate()
	{
		m_CurrentSpeed = m_CurrentSpeed + 15;
		cout<<"Action: Accelarate. Driving @"<< m_CurrentSpeed << "mph" << endl;
	}

	//Reduce the Speed by Brake
	void Brake()
	{
		m_CurrentSpeed = m_CurrentSpeed - 15;
		cout<<"Acction Brake. Driving  @"<< m_CurrentSpeed << "mph" << endl;
	}
};

3. Inheritance Syntax – The CCar Class

The syntax of the inheritance can be understood from the following picture:

Inheritance Syntax
Inheritance Syntax | Source

The figure shows that CCar is the new class we are going to create and this class will inherit common properties and behavior from existing class CVehicle. Remember that CVehicle class was created by us in the previous section. In our example, CCar is the class “Derived” from the existing “Base” class CVehicle. The public keyword encircled here shows the mode of the inheritance. The mode of the inheritance here is public. We will look at the mode of inheritance in the later sections.

Now have a look at the code given below:

class CCar : public CVehicle
{
private:
	int m_trunk;

public:
	CCar(int trunk)
	{
		m_trunk = trunk;
	}

	void PrintCarProps()
	{

		PrintVehicleProps();
		cout<< "CCar Properties:" << endl;
		cout<< "========================" << endl;
		if (m_trunk > 0)
			cout<< "Trunk Exists" << endl;
		else
			cout<< "No Trunk" << endl;
		cout<< endl; 
	}
};

The derived class CCar inherits the properties and methods from the base class CVehicle. The CCar class a new member or I can say a member specific to the class CCar. This new member m_trunk is used to specify whether a car has a storage space or not. Note that the base class properties m_CurrentSpeed, m_FuelLevel are accessed here on the derived class. In public inheritance (Mode of inheritance), the derived class can access all the private and protected members of the base class.

5. The CTruck Class [Inheritance]

The truck class also derived from the CVehicle class and uses the common properties and behaviors defined in the CVehicle class. But, comparing with the CCar it does not care about the Trunk and in place of that it deals with the property like crane type and crane length. The CTruck class implementation is shown in the below code:

class CTruck : public CVehicle
{
private:
	int m_CraneType; //0-Hydralic. 1-Pneumatic
	int m_CraneLength;

public:
	CTruck(int type, int length)
	{
		if (m_CraneType == 0 || m_CraneType == 1)
			m_CraneType = type;
		else
			m_CraneType = 0;

		m_CraneLength = length; 
	}

	void PrintTruckProps()
	{
		char type[15];
		if (m_CraneType == 0)
			strcpy(type, "Hydralic");
		else
			strcpy(type, "Pneumatic");

		PrintVehicleProps();
		cout<< "CTruck Properties:" << endl;
		cout<< "========================" << endl;
		cout<< "Crane Type" << type  << endl;
		cout<< "Crane Length" << type << endl;
		cout<< endl; 
	}
};

Note that in both CCar and CTruck classes, the Print function makes use of the base class version of the print method to display the properties. For Example, making a call to PrintTruckProps() will make a call to the base class version of the print method say PrintVehicleProps in our case. In the program main these inherited classes are tested and the result output is shown below:

int main() 
{ 
	//Create Car object and display it property after
	//accelating the car twice
	CCar car(1);
	car.Accelerate();
	car.Accelerate();
	car.PrintCarProps();

	//Create truck object and display properties
	CTruck truck(1,100);
	truck.PrintTruckProps();

	return 0;
} 

Program Output:

Inheritance Program Output
Inheritance Program Output | Source

The Complete Example code is given below:


#include "stdafx.h"
#include <iostream> 
using namespace std; 

class CVehicle
{
protected:
	int m_FuelLevel;
	int m_CurrentSpeed;

protected:
	void PrintVehicleProps()
	{
		cout<< "Base Properties:" << endl;
		cout<< "========================" << endl;
		cout<< "Current Speed:" << m_CurrentSpeed << endl;
		cout<< "Fuel Level:" << m_FuelLevel << endl;
		cout<< endl; 
	}

public:
	//Constructor
	CVehicle()
	{
		m_FuelLevel = 50;
		m_CurrentSpeed = 0;
	}

	//Increase Speed
	void Accelerate()
	{
		m_CurrentSpeed = m_CurrentSpeed + 15;
		cout<<"Action: Accelarate. Driving @"<< m_CurrentSpeed << "mph" << endl;
	}

	//Reduce the Speed by Brake
	void Brake()
	{
		m_CurrentSpeed = m_CurrentSpeed - 15;
		cout<<"Acction Brake. Driving  @"<< m_CurrentSpeed << "mph" << endl;
	}
};

class CCar : public CVehicle
{
private:
	int m_trunk;

public:
	CCar(int trunk)
	{
		m_trunk = trunk;
	}

	void PrintCarProps()
	{

		PrintVehicleProps();
		cout<< "CCar Properties:" << endl;
		cout<< "========================" << endl;
		if (m_trunk > 0)
			cout<< "Trunk Exists" << endl;
		else
			cout<< "No Trunk" << endl;
		cout<< endl; 
	}
};

class CTruck : public CVehicle
{
private:
	int m_CraneType; //0-Hydralic. 1-Pneumatic
	int m_CraneLength;

public:
	CTruck(int type, int length)
	{
		if (m_CraneType == 0 || m_CraneType == 1)
			m_CraneType = type;
		else
			m_CraneType = 0;

		m_CraneLength = length; 
	}

	void PrintTruckProps()
	{
		char type[15];
		if (m_CraneType == 0)
			strcpy(type, "Hydralic");
		else
			strcpy(type, "Pneumatic");

		PrintVehicleProps();
		cout<< "CTruck Properties:" << endl;
		cout<< "========================" << endl;
		cout<< "Crane Type" << type  << endl;
		cout<< "Crane Length" << type << endl;
		cout<< endl; 
	}
};

int main() 
{ 
	//Create Car object and display it property after
	//accelating the car twice
	CCar car(1);
	car.Accelerate();
	car.Accelerate();
	car.PrintCarProps();

	//Create truck object and display properties
	CTruck truck(1,100);
	truck.PrintTruckProps();

	return 0;
} 

6. Access specifiers in inheritance in c++

We know the access to a class’s data member as well as member functions are controlled by the access specifiers. The three access specifiers are private, public and protected. The derived class can access the protected member of the base class. Whereas, the non-derived classes and global function are restricted to access these protected members. The below diagram shows the access specifiers impact over the program structure.

Class Access Specifiers
Class Access Specifiers | Source

The Red arrow shows that only class member functions can access the private member data and private member function. The derived class doesn’t have access to private members. The public member can be accessed anywhere when they have the object of the class. The point that one should not here is that protected scope of a class is meant for the inherited classes still restricting the member access to outside world other than the inherited classes.

7. Private, public, protected inheritance

All examples in this hub shown are public inheritance. In the case of public inheritance (Refer the encircled one in the picture at section 3) the members are inherited as it is. That is, in the derived class,

  • Base class public members are inherited as public members in derived class
  • Base class private members are not inherited to derived class
  • Base class protected members are inherited as protected in derived class

To do private inheritance, in the syntax picture replace the public as private. Do the same for protected inheritance also.

In the protected inheritance, in the derived class,

  • Base class public members are inherited as protected members in derived class
  • Base class private members are not inherited to derived class
  • Base class protected members are inherited as protected in derived class

So the protected inheritance means all the inherited members as protected.

In the private inheritance, in the derived class,

  • Base class public members are inherited as private members in derived class
  • Base class private members are not inherited to derived class
  • Base class protected members are inherited as private in derived class

We will see other inheritance topics in coming hubs. Thanks.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Raja 2 years ago

      What is difference between Inheritance and aggregation? Why we need to prefer inheritance over aggregation?

    • sirama profile image
      Author

      sirama 2 years ago

      It depends on the design. For Example let us say "A Car is a Vehicle", "A Bus is also a vehicle". In this case Car should be derived from Vehicle and it is a kind of vehicle. Whatever characteristics exposed by vehicle is also exposed by Car also. Inheritance suits here.

      "A Car has a clutch to change gears". A Car is not a clutch. Of-course. But is may contain a clutch to switch the gears. In this case the clutch can go as an aggregated member of a class. Simply, CCar contains CClutch.

      Hope it answers your question.

    Click to Rate This Article