Inheritance is a mechanism in object-oriented programming where a new class is derived from an existing class. The new class inherits all the properties and behavior of the existing class and can also add its own properties and behavior.
Different types of Inheritance supported in C++ are:
- Single Inheritance: A derived class is derived from a single base class.
- Multiple Inheritance: A derived class is derived from multiple base classes.
- Hierarchical Inheritance: Multiple derived classes are derived from a single base class.
- Multilevel Inheritance: A derived class is derived from a base class, which is again derived from another base class.
- Hybrid Inheritance: Combination of multiple inheritance and hierarchical inheritance.
Here is an example of multiple inheritance:
using namespace std;
// Base class 1
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Base class 2
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() {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
int area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << area << endl;
// Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
In the above example, the Rectangle class is derived from two base classes Shape and PaintCost. The Shape class provides the width and height properties, while the PaintCost class provides the cost calculation method. The Rectangle class inherits both these properties and methods and adds its own method getArea() to calculate the area of the rectangle.
No comments:
Post a Comment
If you have any doubts, please let me know