Multiple Inheritance in C++
Inheritance in which a derived class is derived from several base class is known as multiple inheritance.
A class can inherit the attributes of two or more classes as shown in fig. below. This is known as multiple inheritance.
Multiple inheritance allows us to combine the features of several existing classes as a starting point for defining new classes. It is like a child inheriting the physical features of one parent and the intelligence of another.
The syntax of a derived class with multiple base class is as follows:
class D : visibility B-1, visibility B-2... { ... ... (Body of D) ... };
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(void); };
Classes 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 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 P { protected: int m; //from the class M int n; //from the class N public: void get_m(int); //from the class M void get_n(int); //from the class N void display(void); //own member };
The main() function of the program based on the above defined class P may be written as follows:
main() { P x; x.get_m(10); x.get_n(15); x.display(); }
1 Response
[…] Multiple Inheritance […]