What is multiple inheritance? What are the potential pitfalls of multiple inheritance? How would you avoid multiple inheritance?
Deriving a class from more than one direct base class is called multiple inheritance. In the
following example, classes A, B, and C are direct base classes for the derived class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
The order of derivation is relevant only to determine the order of default initialization by
constructors and cleanup by destructors.
Potential pitfalls of Multiple Inheritance are:
1. Ambiguity
2. It's slow
3.
The “Common Ancestor” problem. For example, if class B and class C derived from
class A and if class D derived from class B and class C, then class D will have 2 copies of
class A that might lead to inconsistency, as the class doesn't know which copy it is
viewing.
A
/\
BC
\/
D
Now D has 2 copies of class A.
following example, classes A, B, and C are direct base classes for the derived class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
The order of derivation is relevant only to determine the order of default initialization by
constructors and cleanup by destructors.
Potential pitfalls of Multiple Inheritance are:
1. Ambiguity
2. It's slow
3.
The “Common Ancestor” problem. For example, if class B and class C derived from
class A and if class D derived from class B and class C, then class D will have 2 copies of
class A that might lead to inconsistency, as the class doesn't know which copy it is
viewing.
A
/\
BC
\/
D
Now D has 2 copies of class A.
Comments
Post a Comment
https://gengwg.blogspot.com/