Saturday 2 October 2010

Multiple Inheritance



Multiple Inheritance:
When a class is derived from more than one class then that type of inheritance is called as multiple inheritance.
The general form of multiple inheritance is:
Syntax:
class <derived class name>:<access specifier><base class1>,
<access specifier><base class2 >,
<access specifier><base class3 >
Example 4:
#include<iostream.h>
#include<conio.h>
class A
{
private:
int a;
public:
void setA(int x)
{
a=x;
}
void showA()
{
cout<<”\nA=”<<a;
}
};
class B
{
private:
int b;
public:
void setB(int x)
{
b=x;
}
void showB()
{
cout<<”\nB=”<<b;
}
};

class C: public A, public B  //inheriting multiple classes
{
private:
int c;
public:
void setC(int x)
{
c=x;
}
void show()
{
cout<<”\nC=”<<c;
}
};

void main()
{
A objA;
B objB;
C objC;
clrscr();

//calling class A methods
cout<<”\n calling class A methods”;
objA.setA(10);
objA.showA();

//calling class B methods
cout<<”\n calling class B methods”;
objB.setB(20);
obj.show();

//calling class C methods
cout<<”\n calling class C methods”;
objC.setA(10);
objC.setB(20);
objC.setC(30);
objC.showA();
objC.showB();
objC.showC ();
}

Output:
Calling class A methods
A=10
Calling class B methods
B=20
Calling class C methods
A=10
B=20
C=30
From the above example it can be seen that Class C has inherited the member functions of Class A, B.


Types of Inheritance

No comments:

Post a Comment