Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the extended syntax:
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example
#include<iostream.h>
#include<conio.h>
class first
{
public:
int a;
};
class sec
{
public:
int b;
};
class third:public sec,public first
{
public:
int c;
void get()
{
cin>>a>>b>>c;
}
void disp()
{
cout<<a*b*c;
}
};
int main()
{
third t;
t.get();
t.disp();
getch();
return 0;
}
ex 2:
#include<iostream.h>
#include<conio.h>
class first
{
int a;
public:
void get()
{
cin>>a;}
int disp()
{return a;}
};
class second
{
int b;
public:
void getsec(){
cin>>b;
}
int dispsec()
{
return b;}
};
class third:public first,public second
{
public:
void getfinal()
{
get();
getsec();
}
void dispfinal()
{
cout<<"ans="<<disp()+dispsec();
}
};
main()
{
third t1;
t1.getfinal();
t1.dispfinal();
getch();
}
ex 3:
#include<iostream.h>
#include<conio.h>
class first
{protected:
int a;
int b;
public:
void get()
{cout<<"enter a and b";
cin>>a>>b;
}
int sum()
{
return a+b;
}
};
class second: protected first
{
int c;
public:
void getsec()
{
get();
cout<<"enter value of c";
cin>>c;
}
int calc()
{
return sum()+c;
}
};
class third:protected second
{
int d;
public:
void getthird()
{
getsec();
cout<<"enter value of d";
cin>>d;
}
void calcfinal()
{
cout<<calc()+d;
}
};
main()
{
third t1;
t1.getthird();
t1.calcfinal();
getch();
}
In C++ programming, a class be can derived from a derived class which is known as multilevel inhertiance. For example:
class A { .... ... .... }; class B : public A { .... ... .... }; class C : public B { .... ... .... };
In this example, class B is derived from class A and class C is derived from derived class B.
Example to Demonstrate the Multilevel Inheritance
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
Output
Base class content.
multple inheritance and multilevel
Reviewed by Shobhit Goel
on
May 05, 2015
Rating:
No comments:
Post a Comment