Multiple Inheritance
In multiple inheritance a class can access the property of more than one class. This inheritance is use for multiple accessing of properties. In multiple inheritance ambiguty is
occured when same name function is declare in both class and the object is confuse with function is called.
syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following
example −
#include <iostream.h>
#include <conio.h>
// Base Class
class Shape
{
public:
void getwidth(int w) {
width = w;
}
void getheight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Base class Cost
class cost
{
public:
int getCost(int area) {
return area * 120;
}
};
// Derived class
class Rectangle: public Shape, public Cost
{
public:
int getArea()
{
int a=width * height;
return a;
}
};
void main()
{
Rectangle Rect;
int area;
Rect.getwidth(5);
Rect.getheight(7);
area = Rect.getArea();
cout << "Total area: " << Rect.getArea() << endl;
cout << "Total cost: Rs." << Rect.getCost(area) << endl;
getch();
}
Run it
Comments
Post a Comment