Written by Sai Sandeep Thota on March 24, 2013 in C++ > Programming

What is Multilevel Inheritance in C++

GET ALERTS:

Get our Latest updates delivered to your mailbox!

We have discussed about what is Inheritance and what is Single Inheritance. Today let us discuss about What is Multilevel Inheritance in C++.

In Multilevel Inheritance a derived class can also inherited by another class. For instance in the program below we have a base class and two derived classes. We are inheriting Base class in Derived1 class and inheriting Derived1 class in Derived2 class. So when a derived is inherited by another class then it creates Multiple Levels and this is know an Multi-level Inheritance.

multi-level

Coming to the program below, We are defining a base class and some functions in it. The base class is being inherited by derived1 class and we are multiplying the values of i and j and storing them in the variable k. As we already know that inheritance allows the usage of its variables and functions in the derived functions. In derived2 we are inheriting derived1 and subtracting i and j and storing them in m variable. As derived1 already have the access to base class, so that derived2 also will have access to base variables and functions.

In main program we are defining a object for each class and passing them into respective variables and displaying them using the respective functions.

#include<conio.h>
#include<iostream.h>

class base {
	protected:
	int i, j;
	public:
	void setij(int a, int b) {
		i=a; j=b;
	}
	void showij() {
		cout<<"\ni="<<i<<"\tj="<<j;
	}
};

class derived1 : public base {
	protected:
	int k;
	public:
	void setk() {
		k=i*j;
	}
	void showk() {
		cout<<"\nk="<<k;
	}
};

class derived2 : public derived1 {
	int m;
	public:
	void setm() {
		m=i-j;
	}
	void showm() {
		cout<<"\nm="<<m;
	}
};

void main() {
	derived1 ob1;
	derived2 ob2;
	clrscr();
	ob1.setij(10,20);
	ob1.showij();
	ob1.setk();
	ob2.setij(15,5);
	ob2.showij();
	ob2.setk();
	ob2.showk();
	ob2.setm();
	ob2.showm();
	getch();
}

Output:
multi-level-output

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: