C++ Multilevel inheritance

When a class is derived from another derived class is called multilevel inheritance. It is implemented by defining at least three classes. In multilevel inheritance, there is one base class and the remaining two is derived class.

 

Syntax:

class base_class_name

{

private:

…………….

public:

…………….

protected:

…………….

};

class derived_class_name1 : public base_class_name

{

private:

……………

public:

……………

protected:

……………

};

class derived_class_name2 : public derived_class_name1

{

private:

…………….

public:

…………….

protected:

…………….

};

Program:

/*PROGRAM TO IMPLEMENT MULTI LEVEL INHERITANCE BY USING DEFAULT CONSTRUCTOR IN ALL CLASSES USING PUBLIC VISIBILITY MODE*/

#include<conio.h>

#include<iostream.h>

#include<stdio.h>

class base

{

char name[10];

int roll_no;

public:

base()

{

cout<<“Enter name: “;

gets(name);

cout<<“Enter roll number: “;

cin>>roll_no;

}

void show1()

{

cout<<“Name of the student is: “<<name<<endl;

cout<<“Roll number of the student is:

“<<roll_no<<endl;

}

~base()

{

cout<<“Destructor of base class is executed”<<endl;

}

};

class derived1:public base

{

int marks;

public:

derived1():base()

{

cout<<“Enter marks: “;

cin>>marks;

}

void show2()

{

cout<<“Marks of the student are: “<<marks<<endl;

}

~derived1()

{

cout<<“Destructor of first derived class is

executed”<<endl;

}

};

class derived2:public derived1

{

int age;

char cls[6];

public:

derived2():derived1()

{

cout<<“Enter age: “;

cin>>age;

cout<<“Enter class of the student: “;

cin>>cls;

}

void show3()

{

cout<<“Age of the student is: “<<age<<endl;

cout<<“Class of the student is: “<<cls<<endl;

}

~derived2()

{

cout<<“Destructor of second derived class is

executed”<<endl;

}

};

void main()

{

clrscr();

{

derived2 d1;

d1.show1();

d1.show2();

d1.show3();

}

getch();

}

Leave a Reply

Your email address will not be published. Required fields are marked *