C++ multiple inheritance

C++ multiple inheritance

A class can inherit the attribute of two or more classes show in the below figure.

multiple inheritance pic in c++

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,……
{
//body of D class
………..
………..
………..
};

where visibility may be either public or private. The base classes are separated by commas.Example

Class P: public M, public N
{
public:
void display();
};
Classes above example M and N have been specified as follows
class M
{
protected:
int m;
public:
void get_m(int)
};
void M:: get_m(int x)
{
m=x;
}
class N
{
protected:
int n;
public:
void get_n(int);
};
void 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
{
protected:
int m; // from M
int n; // from N
public:
void get_m(int); // from M
void get_n(int); // from N
void display(); // own member
};
The member function display() can be defined as follows
void 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

#include < iostream >
using namespace std;
class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;
public:
void get_n();
};
class P:public M,public N
{
public:
void display();
};
void M:: get_m(int x)
{
m=x;
}
class N
{
protected:
int n;
public:
void get_n(int);
};
void N:: get_n(int 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
{
protected:
int m; \\ from M
int n; \\from N
public:
void get_m(int); // from M
void get_n(int); // from N
void display(void); // own member
}; The member function display() can be defined as follows:
void 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();
}