CPP Tutorial



C++ POLYMORPHISM


Polymorphism in C++

Polymorphism means "many forms". In C++, it allows functions or methods to behave differently based on the object that calls them. This helps to write flexible and reusable code.

Types of Polymorphism:

  • Compile-time Polymorphism: Achieved using function overloading and operator overloading.
  • Run-time Polymorphism: Achieved using virtual functions and inheritance.

Run-time Polymorphism with Virtual Functions:

This allows a derived class to override a function from the base class. The function to call is decided at run time based on the object type.

Example:

#include <iostream>
using namespace std;

class Animal {
  public:
    virtual void sound() {
      cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
  public:
    void sound() override {
      cout << "Dog barks" << endl;
    }
};

class Cat : public Animal {
  public:
    void sound() override {
      cout << "Cat meows" << endl;
    }
};

int main() {
  Animal* animal;

  Dog myDog;
  Cat myCat;

  animal = &myDog;
  animal->sound();   // Calls Dog's sound()

  animal = &myCat;
  animal->sound();   // Calls Cat's sound()

  return 0;
}
  

πŸ–¨οΈ Output:

Dog barks
Cat meows

πŸ” Explanation:

  • sound() is declared as virtual in the base class Animal.
  • The pointer animal points to different derived objects (Dog, Cat).
  • The correct sound() function is called based on the actual object, not the pointer type.
  • This is called dynamic dispatch or run-time polymorphism.

Summary

  • Polymorphism allows methods to behave differently based on object type.
  • Run-time polymorphism uses virtual functions and inheritance.
  • It’s very useful in designing flexible and maintainable code.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review