Object-Oriented Programming

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass.

We can treat objects of similar kinds in a uniform way.

There are 2 types of polymorphism in C++:

  1. Compile Time Polymorphism (achieved through Function Overloading)
  2. Runtime Polymorphism (achieved through Virtual Functions and Function Overriding)

What is the advantage of polymorphism?

Polymorphism provides flexibility and reusability in code. It allows objects of different types to be treated as objects of a common type, facilitating code maintenance and extensibility. More about these ideas in Object-Oriented Design

Thanks to polymorphism, we can do some really cool things with pointers (and that’s actually one of the main use cases of Pointers). See Static vs. Dynamic Type of Pointer

Example from https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm

Note: I have this shape example that I wrote myself in Constructor.

#include <iostream>
using namespace std;
 
class Shape {
   protected:
      int width, height;
 
   public:
      Shape(int a = 0, int b = 0){
         width = a;
         height = b;
      }
      virtual int area() { // Virtual keyword is SUPER important, because child is going to override it
         cout << "Parent class area :" << width * height << endl;
         return width * height; 
      }
};
class Rectangle: public Shape {
   public:
      Rectangle(int a = 0, int b = 0):Shape(a, b) { }
 
      int area () {
         cout << "Rectangle class area :" << width * height << endl;
         return (width * height);
      }
};
 
class Triangle: public Shape {
   public:
      Triangle( int a = 0, int b = 0):Shape(a, b) { }
 
      int area () {
         cout << "Triangle class area :" << (width * height)/2 << endl;
         return (width * height / 2);
      }
};

In the main loop,

Shape *shape;
Rectangle rec(10,7);
Triangle  tri(10,5);
 
shape = &rec;
shape->area(); // Parent class area :70
 
shape = &tri;
shape->area(); //Parent class area :25

You should be careful about this, see Virtual Function.

Some dangerous issues with Polymorphism

These are some super dangerous issues that arise due to polymorphism, and first introduced in CS247.

See Polymorphic Big Five.