1. Ambiguity of multiple inheritance
When using multiple inheritance, if more than one parent class has a variable with the same name defined, two semantics will appear. WORKAROUND: Use:: declaration scope
#include <iostream>using namespacestd;classa{ Public: intx; inty; A () {cout<<"A Default constructor"<<Endl; X=1; Y=1; }};classb{ Public: intx; inty; B () {cout<<"B Default constructor"<<Endl; X=2; Y=2; }};classC: PublicA Publicb{ Public: intx; inty; C () {cout<<"C Default constructor"<<Endl; X=3; Y=3; }};intMain () {C C; cout<< c.x << Endl;//3cout << c.a::x << Endl;//1cout << c.b::x << Endl;//2cout << c.c::x << Endl;//3 return 0;}
2. Multiple base class replicas
inheritance, which produces multiple copies of the base class without virtual inheritance
#include <iostream>using namespacestd;classa{ Public: intx; inty; A () {cout<<"A Default constructor"<<Endl; X=1; Y=1; }};classB: Publica{ Public: B () {cout<<"B Default constructor"<<Endl; }};classC: Publica{ Public: C () {cout<<"C Default constructor"<<Endl; }};classD: PublicB Publicc{ Public: D () {cout<<"D Default constructor"<<Endl; }};intMain () {D D; //d.x = 20; Error x not clear//d.a::x = 20; Error, base Class A is not clearD.b::x = -; cout<< d.b::x << Endl;// -cout << d.c::x << Endl;//1 not changed return 0;}
Note that the constructor for a has been used two times. The B and C constructors are in the same order as they were declared when they were inherited.
3. Virtual inheritance
Use virtual when inheriting, so that no base class copies are generated
#include <iostream>using namespacestd;classa{ Public: intx; inty; A () {cout<<"A Default constructor"<<Endl; X=1; Y=1; }};classB:Virtual Publica{ Public: B () {cout<<"B Default constructor"<<Endl; }};classC:Virtual Publica{ Public: C () {cout<<"C Default constructor"<<Endl; }};classD: PublicB Publicc{ Public: D () {cout<<"D Default constructor"<<Endl; }};intMain () {D D; D.b::x= -; cout<< d.x << Endl;// -cout << d.a::x << Endl;// -cout << d.b::x << Endl;// -cout << d.c::x << Endl;// - return 0;}
Note: The constructor for a is used only once. And all the X are unified, there is no ambiguity.
"C + +" multiple inheritance