Multilevel Inheritance in C ++

 Inheritance In C++





Inheritance is a process of creating new classes from existing classes. Existing class is known as base class and new class is known as derived class. The derived class is also called as sub class or child class and base class is called as super class or parent class. The derived class inherits all the features of base class .

The main advantages of of inheritance are

reusability

to increase the reliability of the code

to add more enhancements to the base class

Types of Inheritance:

2. Multilevel Inheritance:

The class A serves as a base class for derived class B, which then becomes bases class for derived class C. The class b is known as intermediate base class. It provides link between A and C. The chain A-B-C is known as inheritance path. Base class A is just like grand father in our family, intermediate class B is like father and derived class C is like child in our family. 

How to define Derived class:

The singly derived class is same as that of ordinary class.  Derived class consist following components,

the class keyword

the name of the derived class

a single colon

the type of derivation(private,public,protected)

the name of the base class or parent class

the remainder of the class definition


The general syntax for Multilevel Inheritance

class A

{

private:

//data member

public:

//member functions

};


class B : public A

{

private:

//data member

public:

//member functions

};

class C : public B

{

private:

//data member

public:

//member functions

};


A program demonstrate the use of multilevel inheritance in C++

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class student

{

protected:

int rollno;

public:

void get_number(int);

void put_number(void);

};//end of class definition

void student :: get_number(int a)

{

rollno=a;

}

void student :: put_number()

{

cout<<”Roll no is”<<rollno<<endl;

}

class test : public student //first level derivation

{

protected:

float sub1;

float sub2;

public:

void get_marks(float,float);

void put_marks();

};//end of class definition

void test::get_marks(float x, float y)

{

sub1=x;

sub2=y;

}

void test :: put_marks()

{

cout<<”Marks in frist subject”<<sub1<<endl;

cout<<”Marks in second subject ”<<sub2<<endl;

}

void result : public test //second level of derivation

{

private:

float total;

public :

void display(void);

};

void result :: display(void)

{

total=sub1+sub2;

put_number();

put_marks();

cout<<”Total is”<<total<<endl;

}


void main()

{

result r;

r.get_number(90);

r.get_marks(88.5, 65.5);

r.display();

}


Output:

Roll no is 90

Marks in first subject 88.5

Marks in second subject 65.5

Total is 154.0

टिप्पणी पोस्ट करा

0 टिप्पण्या