MULTILEVEL

It is not uncommon that a class is derived from another derived class. 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.Class B is known as an intermediate base class since it provides a link for the inheritance between A and C.The chain ABC is known as inheritance path.

Multiple inheritance
Multiple inheritance

A derived class with multilevel inheritance is declared as follows:
class A{……..};
class B: public A{……};
class C: public B {……};

1.Example for multilevel inheritance

#include <iostream> 
using namespace std; 
class Animal { 
public: 
void eat() { 
cout<<"Eating..."<<endl; 
} 
}; 
class Dog: public Animal 
{ 
public: 
void bark(){ 
cout<<"Barking..."<<endl; 
} 
}; 
class BabyDog: public Dog 
{ 
public: 
void weep() { 
cout<<"Weeping..."; 
} 
}; 
int main(void) { 
BabyDog d1; 
d1.eat(); 
d1.bark(); 
d1.weep(); 
return 0; 
} 
 
Output:
Eating...
Barking...
Weeping...

2.Multiple Inheritance:

A class inherit the attributes of two or more classes.this is known as multiple inheritance . Multiple inheritance allows us to combine the feature of several existing classes as a starting point for defining new classes.

Multiple Inheritance

class D: visibility B-1,visibility B-2…
{
……
…..(Body of D)
…..
}

Example for multiple Inheritance:

#include<iostream>
using namespace std;
class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;
public:
void get_n(int);
};
class P: public M,public N
{
public:
void display(void);
};
void M::get_m(int x)
{
m=x;
}
void N::gat_n(int y)
{
n=y;
}
void P::display(void)
{
count<<"m="<<m<<"\n";
count<<"n="<<n<<"\n";
count<<"m*n="<<m*n<<"\n";
}
int main()
{
p;
p.get_m(10);
p.get_n(20);
p.display();
return 0;
}

OUTPUT:
m=10
n=20
m*n=200
Translate »