Multiple inheritance in C++
Hello everyone, in this tutorial we learn about MULTIPLE INHERITANCE in C++. Before we start I expected that you all are aware of inheritance,
INHERITANCE means, the mechanism of deriving a new class from an old class. The old class is called the base class and the new one is called Subclass or Derived class.
Multiple Inheritance
Multiple inheritance means a class can be derived from more than one parents. It allows us to combine the features of several existing classes into a single class.
Syntax:
class A { properties; methods; }; class B { properties; methods; }; class C :Access_specifier A ,Access_specifier B { properties; methods; };
In real life, there are many examples of Multiple inheritances. A child has a character of both his/her father and mother.
Code snippet: Multiple Inheritance in C++
#include <iostream> using namespace std; class Father { public: Father() { cout << "He is a father." << endl; } }; class Mother { public: Mother() { cout << "She is a mother." << endl; } }; class Son: public Father, public Mother { }; int main() { Son b1; return 0; }
OUTPUT:
He is a Father. She is a Mother.
In this code, Class Son is derived from base classes Father and Mother. It makes sense because Son is a child of a father as well as the mother, So the public features of both Father and Mother are inherited to Son.
Ambiguity in Multiple Inheritance in C++:
In multiple inheritances, a single class is derived from two or more parent classes. So, there will be a possibility that two or more parents have the same-named member function. If the object of child class needs to access one of the same-named member function then it results in ambiguity. The compiler is confused as a method of which class to call on executing the call statement.
For example:
#include <iostream> using namespace std; class A { public: Father() { cout << "He is a father." << endl; } }; class B { public: Mother() { cout << "She is a mother." << endl; } }; class Son: public A, public B { }; int main() { Son b1; b1.Father(); /*Causes ambiguity*/ return 0; }
Ambiguity Resolution:
This problem can be solved using scope resolution function to specify which function to class either Class A or Class B.
int main() { Son b; b.A::Father(); b.B::Father(); return 0; }
OUTPUT:
He is a father. She is a mother.
Do let me know in the comment section if you have any doubt.
Also read: Change case of a character using bit manipulation in C++
Leave a Reply