Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

Multilevel Inheritance Sample Program in C++

|| 0

Multilevel Inheritance Sample Program in C++
Stechies

What is Multilevel Inheritance?

Multilevel inheritance is the process of deriving a class from another class which was further derived from another base class. For example, class ‘C’ is derived from class ‘B’, which is further derived from the class ‘A’. Here, class ‘A’ is the base class for class ‘B’, which is again the base class for ‘C’. Therefore, class ‘A’ is called base class, class ‘B’ is called intermediate base class, and class ‘C’ is called derived class.

Multilevel inheritance sample program:

# include <iostream.h>
# include <conio.h>
class stu //Base class
{
int id;
char name[20];
public:                                           //If not declared, data members are by default defined as private//
void getstu()
{
cout << “Enter stuid, name”;
cin >> id >> name;
}
void putstu()
{
cout << “ID=” << id << endl;
cout << “Name=” << name << endl;
}
}
class marks: public stu                    //Intermediate Base class//
{
protected:                                       //without this command, data members will not be available next//
int m1, m2, m3;                             // without ‘protected:’ command, m1, m2, & m3 are private members//
public:
void getmarks()
{
cout << “Enter 3 subject marks:”;
cin >> m1 >> m2 >> m3;
}
void putmarks()
{
cout << “M1=” << m1 << endl;
cout << “M2=” << m2 << endl;
cout << “M3=” << m3 << endl;
}
}
class result : public marks;                       //Derived Class//
{
int tot;
float avg;
public :
void show()
{
tot=m1+m2+m3;
avg=tot/3.0;
cout << “Total=” << tot << endl;
cout << “Average=” << avg << endl;
}
}
void main()
{
result r //Object
r.getstu();
r.getmarks();
r.putstu();
r.putmarks();
r.show();
getch();
}


Advertisement
Advertisement
Advertisement