OOPS - [C++ Multilevel Inheritance]

♠ Posted by Unknown in at 03:46

Multilevel Inheritance


When a class is derived form another derived class is called multilevel inheritance. In the following figure 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 ABC is known as inheritance path.
           
            class A{…………};                         //Base Class
            class B: public A{…………};       // B derived from A
            class C: public B{…………};       // C derived from B


Image: Multi Level Inheritance
Example:

#include<iostream.h>
#include<conio.h>
class Student //Base Class
{
 protected:
            int rno;
 public:
            void get_number(int);
            void put_number(void);
};

void Student::get_number(int a)
{ rno = a; }

void Student::put_number(void)
{
 cout<<"Roll Number :"<<rno<<endl;
}

class Test: public Student //Intermediate Base Class
{
 protected:
            int sub1;
            int sub2;
 public:
            void get_marks(int , int );
            void put_marks(void);
};
void Test::get_marks(int x, int y)
{
 sub1 = x;
 sub2 = y;
}
void Test::put_marks(void)
{
 cout<<"Subject-1 : "<<sub1<<endl;
 cout<<"Subject-2 :"<<sub2<<endl;
}

class Result: public Test //Derived Class
{
            int total;
 public:
            void display(void);
};
void Result::display(void)
{
 total = sub1 + sub2;
 put_number();
 put_marks();
 cout<<"Total : "<<total<<endl;
}

void main()
{
 clrscr();
 Result stud;
 stud.get_number(111);
 stud.get_marks(56,78);
 stud.display();
 getch();
}

0 comments:

Post a Comment