What is the real significance(use) of polymorphism
Classic answer: Imagine a base class Shape
. It exposes a GetArea
method. Imagine a Square
class and a Rectangle
class, and a Circle
class. Instead of creating separate GetSquareArea
, GetRectangleArea
and GetCircleArea
methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape
you use, you just call GetArea
and you get your result, independent of which concrete type is it.
Have a look at this code:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual float GetArea() = 0;
};
class Rectangle : public Shape
{
public:
Rectangle(float a) { this->a = a; }
float GetArea() { return a * a; }
private:
float a;
};
class Circle : public Shape
{
public:
Circle(float r) { this->r = r; }
float GetArea() { return 3.14f * r * r; }
private:
float r;
};
int main()
{
Shape *a = new Circle(1.0f);
Shape *b = new Rectangle(1.0f);
cout << a->GetArea() << endl;
cout << b->GetArea() << endl;
}
An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.
Have fun learning!
Have you ever added two integers with +
, and then later added an integer to a floating-point number with +
?
Have you ever logged x.toString()
to help you debug something?
I think you probably already appreciate polymorphism, just without knowing the name.