Multilevel Inheritance

It is not uncommon that a class is derived from another derived  class as shown below 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.

A derived class with multilevel inheritance is declared 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 level.

let us consider a simple example.Assume that the test results of a batch of students are stored in 3 different classes.class student stores the roll number,class test stores mark obtain in 2 subject and class result contains the total marks obtain in test.

The class result can inherit the details of the marks obtained in the test and the roll number of student through multilevel inheritance,

Example:

#include<iostream>
using namespace std;
class student
{
protected:
int rollnumber;
public:
void getdata(int);
    void put_number(void);     
};
void student :: getdata(int a)
{
rollnumber=a;
}
void student :: put_number()
{
cout<<"roll number is"<<rollnumber<<"\n";
}
class test : public student
{
protected:
float sub1;
float sub2;
public:
void get_marks(float x,float y);
void put_marks(void);
};
void test :: get_marks(float x,float y)
{
sub1=x;
sub2=y;
}
void test :: put_marks()
{
cout<<"\nmarks in sub1"<<sub1<<"\n";
cout<<"\nmarks in sub2"<<sub2<<"\n";
}
class result : public test
{
private:
float total;
public:
void display(void);
};
void result :: display(void)
{
total=sub1+sub2;
put_number();
put_marks();
cout<<"\n total="<<total<<"\n";
}
int main()
{
result student1;
student1.getdata(111);
student1.get_marks(75.0,59.5);
student1.display();
return 0;

}

Output: 


0 comments:

Copyright © 2013 free coding