C++ Polymorphism

🎭 C++ Polymorphism – One Function, Many Forms!

In C++, polymorphism allows you to use a single function name to represent different behaviors across different derived classes. This enables the same code to behave in various ways depending on the object type. Cool, right? 😎

🔍 What is Polymorphism?

Polymorphism means “many forms.” In programming, it means that a single function or method can have different implementations depending on the type of the object calling it. This is one of the cornerstones of Object-Oriented Programming (OOP).

In C++, polymorphism is mainly achieved through virtual functions and function overriding.

📦 Types of Polymorphism

  • Compile-Time Polymorphism: Decided at compile time (e.g., function overloading)
  • Run-Time Polymorphism: Decided at runtime (e.g., function overriding with virtual functions)

🔧 Example: Runtime Polymorphism Using Virtual Functions

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() {
        cout << "Animal makes 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 d;
    Cat c;

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

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

    return 0;
}
  

Try It Now

🔑 Key Concepts of Polymorphism

  • Single interface, multiple implementations
  • Achieved using virtual functions and function overriding
  • Allows base class pointers to call derived class functions at runtime
  • Improves flexibility and maintainability of code

📚 Real-World Example

Imagine a system for drawing shapes. You can have a base class Shape with a method draw(). Derived classes like Circle and Rectangle can override draw() to provide specific implementations for each shape. By using polymorphism, you can handle all shapes using the same interface!

⚠️ Polymorphism Pitfalls

  • Make sure the base class method is marked as virtual
  • Use override keyword in derived classes (C++11 and beyond)
  • Ensure that the correct function is called by using base class pointers or references

🧾 Summary

  • Polymorphism allows a single function to work with multiple object types
  • Use virtual functions and override in C++ to achieve runtime polymorphism
  • It improves code flexibility, reuse, and maintainability
  • Remember: one function name, many behaviors! 🎭