Multilevel Inheritance And Its C++ Program - Coding Bot

Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Tuesday, 28 May 2013

Multilevel Inheritance And Its C++ Program

Hello Guys,
As I have already discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its second type, that is, Multilevel Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

So in Multilevel Inheritance, we actually have 2 Base Classes in total and 1 Child class. The class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.

The class B is known as Intermediate Base Class since it provides a link for the inheritance between A and C. The chain A B C is known as Inheritance Path. For pictorial representation, follow this link: Inheritance.

A derived class with multilevel inheritance is declared as follows:

class A {.....};            // Base class
class B: public A {.....};             // B derived from A
class C: public B {.....};             // C derived from B

This process can be extended to any number of levels. Let us understand this concept by a simple C++ program:

C++ Program For Multi-level Inheritance:


/* Double-Click To Select Code */

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

class student
{
 protected:
  int roll;
 public:
  void get_number(int a)
  {
   roll = a;
  }

  void put_number()
  {
   cout<<"Roll Number: "<<roll<<"\n";
  }
};

class test : public student
{
 protected:
  float sub1;
  float sub2;
 public:
  void get_marks(float x,float y)
  {
   sub1 = x;
   sub2 = y;
  }

  void put_marks()
  {
   cout<<"Marks in Subject 1 = "<<sub1<<"\n";
   cout<<"Marks in Subject 2 = "<<sub2<<"\n";
  }

};

class result : public test
{
 private:
  float total;
 public:
  void display()
  {
   total = sub1 + sub2;
   put_number();
   put_marks();
   cout<<"Total = "<<total<<"\n";
  }
};

void main()
{
 clrscr();

 result student;
 student.get_number(83);
 student.get_marks(99.0,98.5);
 student.display();

 getch();
}

Program Output:



Multilevel Inheritance In C++

Please Comment If You Liked The Post.


Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: