Multiple Inheritance
- Multiple inheritance is a
concept in which an object or a class can acquire the characteristics and
features from more than one class.
- It is distinct from single
inheritance, where an object or class may only be inherited from one
particular object or class.
- Deriving directly from more
than one class is usually called multiple inheritance.
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:
Syntax :
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
In the above
example,
Class X inherits
the indirect base class A once through class Band once through class C.
However, this may lead to ambiguities because two sub-objects of class A exist,
and both are accessible through class X. You can avoid this ambiguity by
referring to class A using a qualified class name.
Sample Program:
#include <iostream>
using namespace std;
// Base class Shape
class Shape
{
public: void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected: int width; int height;
};
// Base class PaintCost
class PaintCost
{
public: int getCost(int area)
{
return area * 70;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public: int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect; int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea(); // Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl; // Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
#include <iostream>
using namespace std;
// Base class Shape
class Shape
{
public: void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected: int width; int height;
};
// Base class PaintCost
class PaintCost
{
public: int getCost(int area)
{
return area * 70;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public: int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect; int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea(); // Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl; // Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
Output:
Total area : 35
Total paint cost :$2450
Total paint cost :$2450
Advantage:
- Multiple inheritance that
allows a class to inherit the functionalities of more than one base class
thus allowing for modelling complex relationships.
Disadvantage:
- The multiple inheritance that can lead to a lot of confusion when two base classes is implemented in a method with the same name.
Multiple Inheritance
Reviewed by NEERAJ SRIVASTAVA
on
4:10:00 PM
Rating:
No comments: