menu search
brightness_auto
more_vert
Write a class in c++ to demonstrates the example of multilevel inheritance?
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

1 Answer

more_vert
 
verified
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.

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

Related questions

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 1 like thumb_down_off_alt 0 dislike
1 answer

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

648 users

...