Real-World Applications of Inheritance and Polymorphism
Inheritance and polymorphism are two of the core concepts of object-oriented programming, and they are widely used in real-world applications.
Inheritance allows you to create a new class based on an existing class, inheriting all its properties and behaviors. This allows you to create more specialized classes that can be reused and maintained more easily. For example, in a banking application, you could have a base class called "Account" with properties and behaviors common to all types of accounts (e.g. checking, savings, etc.). Then, you could create derived classes for each type of account, inheriting the properties and behaviors of the base class, and adding any new properties or behaviors specific to that type of account.
Polymorphism, on the other hand, allows you to treat objects of different classes in a similar way, as long as they share a common base class or interface. This is achieved by defining virtual functions in the base class and overriding them in the derived classes. For example, in a graphic design application, you could have a base class called "Shape" with a virtual function called "draw()". Then, you could create derived classes for different types of shapes (e.g. circle, rectangle, etc.), each with its own implementation of the "draw()" function. When you want to draw a shape, you can simply call the "draw()" function of a Shape object, regardless of its actual type, and the correct implementation of the function will be called automatically.
Here is an example of inheritance and polymorphism in C++:
#include <iostream>
class Shape {
public:
virtual void draw() {
std::cout << "Drawing a shape" << std::endl;
}
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a circle" << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
std::cout << "Drawing a rectangle" << std::endl;
}
};
int main() {
Shape *shapes[2];
shapes[0] = new Circle();
shapes[1] = new Rectangle();
for (int i = 0; i < 2; i++) {
shapes[i]->draw();
}
return 0;
}
In this example, we have a base class called "Shape" with a virtual function called "draw()". Then, we have two derived classes, "Circle" and "Rectangle", each with its own implementation of the "draw()" function.
In the main function, we create an array of Shape pointers, and assign objects of the derived classes to the elements of the array. When we loop through the array and call the "draw()" function of each element, the correct implementation of the function is called automatically, depending on the actual type of the object. The output of the program is:
Drawing a circle
Drawing a rectangle
This example demonstrates the power and elegance of inheritance and polymorphism in C++, and how they can be used to create flexible and reusable code.