C++ multiple inheritance
A class can inherit the attribute of two or more classes show in the below figure.
This is know as multiple inheritance. Multiple inheritance allows users to combine the features
of several existing classes as a starting point for defining new class. it is like a child(subclass) inheriting the physical features of one parent and the intelligence of another
The stntax of a derived class with multiple base classes is as follows
class D: visibility A, visibility B,……
{
………..
………..
………..
};
|
where visibility may be either public or private. The base classes are separated by
commas.Example
Class P: M, N
{
:
display();
};
Classes above example M and N have been specified as follows
class M
{
:
m;
:
get_m(int)
};
M:: get_m(int x)
{
m=x;
}
class N
{
:
n;
:
get_n(int);
};
N::get_n(int y)
{
n=y;
}
|
The derived P class, as above declared , would , in effect , contain all the members of M and N in addition to its own members as shown in below
class P
{
:
m;
n;
:
get_m(int);
get_n(int);
display();
};
The member function display() can be defined as follows
p:: display()
{
std::cout << "m=" << m << "\n";
std::cout << "n" << n << "\n";
std::cout << "m*n=" << m*n << "\n";
};
The main() function which provides the user interface may be written as follows
main()
{
p p;
p.get_m(10);
p.get_n(20);
p.display();
}
|
PRogram to multiple inheritance
< iostream >
using namespace std;
class M
{
:
m;
:
get_m();
};
class N
{
:
n;
:
get_n();
};
class P: M,public N
{
:
display();
};
M:: get_m( x)
{
m=x;
}
class N
{
:
n;
:
get_n();
};
N:: get_n( y)
{
n=y;
}
|
The derived class P, as declared above, would, in effect, contain all the members of M and N in addition to its own members as shown below
class Program
{
:
m;
n;
:
get_m();
get_n();
display();
};
The member function display() can be defined as follows:
P:display()
{
std::cout << "m=" <
std::cout << "n=" << n << "\n";
std::cout << "m*n=" << m*n << "\n";
};
The main() function which provides the use interface may be written as follows
main()
{
P p;
p.get_m(10);
p.get_n(20);
p.display();
}
|