0 votes
107 views
in Programming by (98.9k points)
edited
Write a class in c++ to demonstrates the example of multilevel inheritance?

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer
#include <iostream>
using namespace std;

// Base class
class Vehicle {
 public:
 Vehicle() {
 cout << "This is a vehicle." << endl;
 }
};

// Derived class 1
class Car : public Vehicle {
 public:
 Car() {
 cout << "This is a car." << endl;
 }
};

// Derived class 2
class Sedan : public Car {
 public:
 Sedan() {
 cout << "This is a sedan." << endl;
 }
};

// Main function
int main() {
 Sedan sedanObj;
 return 0;
}

In this example, we have a base class called Vehicle that is inherited by a derived class called Car, and then Car is further inherited by another derived class called Sedan.

When we create an object of the Sedan class, it will call the constructors of all three classes in order: first Vehicle, then Car, and finally Sedan. This is an example of multilevel inheritance.

The output of running the above code would be:

This is a vehicle.
This is a car.
This is a sedan.

This demonstrates how the derived class Sedan inherits the properties and behavior of both its parent classes, Car and Vehicle.

Related questions

0 votes
1 answer 123 views
0 votes
1 answer 132 views
+1 vote
1 answer 192 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

554 users

...