- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to demonstrate multi-level inheritance
Suppose we have three classes Vehicle, FourWheeler, and Car. The class Vehicle is the base class, the class FourWheeler is derived from it and the class Car is derived from the class FourWheeler. Class Vehicle has a method 'vehicle' that prints 'I am a vehicle', class FourWheeler has a method 'fourWheeler' that prints 'I have four wheels', and class Car has a method 'car' that prints 'I am a car'. So, as this is a multi-level inheritance; we can have access to all the other classes methods from the object of the class Car. We invoke all the methods from a Car object and print the corresponding outputs of the methods.
So, if we invoke the methods in this order, car(), fourWheeler(), and vehicle(), then the output will be −
I am a car I have four wheels I am a vehicle
To solve this, we will follow these steps −
- Define a new class Vehicle.
- Define a function vehicle()
- print("I am a vehicle")
- Define a function vehicle()
- Define a new class FourWheeler inheriting from the class Vehicle.
- Define a function fourWheeler()
- print("I have four wheels")
- Define a function fourWheeler()
- Define a new class Car inheriting from the class FourWheeler.
- Define a function car()
- print("I am a car")
- Define a function car()
Example
Let us see the following implementation to get better understanding −
#include <iostream> using namespace std; class Vehicle{ public: void vehicle(){ cout<<"I am a vehicle\n"; } }; class FourWheeler : public Vehicle{ public: void fourWheeler(){ cout<<"I have four wheels\n"; } }; class Car : public FourWheeler{ public: void car(){ cout<<"I am a car\n"; } }; int main(){ Car obj; obj.car(); obj.fourWheeler(); obj.vehicle(); return 0; }
Input
Car obj; obj.car(); obj.fourWheeler(); obj.vehicle();
Output
I am a car I have four wheels I am a vehicle