Login    New User    Forgot Password    Help      

Multiple Inheritance in C++

GO TO INDEX

Multiple Inheritance in C++

 

Using multiple inheritance in C++

Deriving directly from more than one class is usually called multiple inheritance. Since it's widely believed that this concept complicates the design and debuggers can have a hard time with it, multiple inheritance can be a controversial topic. However, multiple inheritance is an important feature in C++ and C++ programmers think of it as a very good structuring tool.

You can derive a class from any number of base classes. 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 following inheritance graph describes the inheritance relationships of the above example. An arrow points to the direct base class of the class at the tail of the arrow:

inheritance_multiple

The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.

A direct base class cannot appear in the base list of a derived class more than once:

class B1 { /* ... */ };                   // direct base class  
class D : public B1, private B1 { /* ... */ }; // error

However, a derived class can inherit an indirect base class more than once, as shown in the following example:

inheritance_multiple_2
class L { /* ... */ };                  // indirect base class  
class B2 : public L { /* ... */ };  class B3 : public L { /* ... */ };  
class D : public B2, public B3 { /* ... */ }; // valid

In the above example, class D inherits the indirect base class L once through class B2 and once through class B3. However, this may lead to ambiguities because two subobjects of class L exist, and both are accessible through class D. You can avoid this ambiguity by referring to class L using a qualified class name


Example


class Polygon
{
protected int width, height;
public void setParameters (int w,int h)
{
width = w;
height = h;
}
};

class Rectangle : public Polygon
{
public int calculateArea ()
{
return (width*height);
}
};

class Triangle : public Polygon
{
public int calculateArea ()
{
return( (width*height)/2);
}
};

int main ()
{
Rectangle rect;
Triangle trgl;
rect. setParameters (4,5);
trgl. setParameters (4,5);
cout << rect. calculateArea () << endl;
cout << trgl. calculateArea () << endl;
return 0;
}

GO TO INDEX