Polymorphism in C++

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. It enables methods to do different things based on the object it is acting upon, even if the method name and signature are the same.

With polymorphism, a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. How to achieve this?

  1. Declare a virtual member function in base class
  2. Customized implement of the virtual member function in every derived class
  3. Create a base class pointer for a derived class object
  4. Access the derived class member function through base class pointer.

Code Example


Explanation

Abstract Class and Pure Virtual Function

class Animal {
  virtual void move() = 0; // declare pure virtual function for polymorphism
};

Concrete Classes

class Horse : public Animal {
  void move() {
    cout << "Child chass: horse runs with legs" << endl; // implement for horse class
  }
};
class Fish : public Animal {
  void move() {
    cout << "Child chass: fish swims in water" << endl; // implement for fish class
  }
};

Non-virtual Function

class Animal {
  void live() { // non-virtual function, not for polymorphism
    cout << "Parent class: animal lives on earth" << endl;
  }
};

main function

shared_ptr animal[2];
animal[0] = make_shared(); // animal pointer to horse object
animal[1] = make_shared(); // animal pointer to fish object
for (int i = 0; i < 2; ++i) {
  animal[i]->move(); // polymorphism: child function executed
  animal[i]->live(); // not polymorphism: parent function executed
}

Conclusion

Polymorphism allows for flexibility and the ability to program to interfaces rather than specific implementations. It enables a single interface to represent different underlying forms (data types).