Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

inheritance
c++
classes

Inheritance in C++

Educative Answers Team

Inheritance is the ability of a class to derive or inherit methods and properties from another class. There are two types of categories of classes that involve​ inheritance:

  • Derived or Sub Class: A class that inherits properties from another class.

  • Base Class: A class whose properties are inherited by the derived class.

Example

Let’s consider some types of vehicles that you can create classes for (e.g., car, bus, and truck). Now, let’s think of some very basic functions of these vehicles that can be implemented in the classes:

  • Start_Engine()

  • Accelerate()

  • Apply_Brakes()

If the classes for the three mentioned vehicles are created without inheritance, then these functions would need to be written in all three classes. If they are not written, then data duplication will occur since the methods have to be written for each class separately. This will then increase the chance of error and data redundancy – to avoid this, inheritance is used.

​With inheritance, there will be a base class, Vehicle,​ and three derived classes: Car, Bus and Truck.​

svg viewer

Syntax

The syntax below creates​ a derived class which inherits a base class:

class name_of_derived_class : access_mode name_of_base_class
{
  //body of derived class
};

Code

The code snippet below illustrates the usage of inheritance, in OOP, in C++:

#include <bits/stdc++.h> 
using namespace std; 

//Base class 
class Vehicle 
{ 
	public: 
	  int reg_number; 
	
	void Start_engine() 
	{
		cout << "Engine is starting" << endl;
	}
	void Accelerate() 
	{
		cout << "Vehicle is accelerating" << endl;
	}
	void Apply_Brakes() 
	{
		cout << "Brakes are being applied" << endl;
	}
}; 

// Derived class inheriting from Base Class(Vehicle) 
class Car : public Vehicle 
{ 
	public: 
	  int year_made; 
};

// Derived class inheriting from Base Class(Vehicle) 
class Bus : public Vehicle 
{ 
	public: 
	  int passenger_capacity; 
};

// Derived class inheriting from Base Class(Vehicle) 
class Truck : public Vehicle 
{ 
	public: 
	  int model_number; 
}; 

int main() 
{ 
	
		Car corolla;
		
		// An object of Car class has inherited the
		//  property of Vehicle Class
		corolla.reg_number = 3110; 
		corolla.year_made = 2011; 

		cout << "Registration number of vehicle is " << corolla.reg_number << endl; 
		cout << "Vehicle was manufactured in  " << corolla.year_made << endl; 

		corolla.Start_engine();
		corolla.Accelerate();
		
		return 0; 
} 

RELATED TAGS

inheritance
c++
classes
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring