One of the most significant elements of Object-Oriented Programming is polymorphism. Polymorphism in C++ is primarily classified into two types:
Compile-time Function overloading or operator overloading is used to accomplish this form of polymorphism.
Runtime Polymorphism: Function Overriding is used to accomplish this form of polymorphism.
Take a look at the following scenario.
Let's say we have a Shape base class with the following interface.
class Shape {
public:
Shape(int init_x, int init_y);
virtual ~Shape() = default;
virtual void scale(int s) = 0;
protected:
int x;
int y;
};
We now wish to inherit two more classes from it: Rectangle and Circle.
class Rectangle : public Shape {
public:
Rectangle(int init_x, int init_y, int w, int h);
void scale(int s) override;
private:
int width;
int height;
};
class Circle : public Shape {
public:
Circle(int init_x, int init_y, int r);
void scale(int s) override;
private:
int radius;
};
As you may know, the scale function for circle and rectangle forms is implemented differently, hence I can't implement it in the Shape class.
Assume we have a software that saves all the shapes in a vectorShape*> container. (For example, it obtains all of the user's forms at once and stores them in this container.)
We don't know which sort of shape we're working with when we use the scale method on one of the shapes, but it will link our scale method call to the proper implementation.