0
0
C++programming~5 mins

Why polymorphism is needed in C++

Choose your learning style9 modes available
Introduction

Polymorphism lets us use one interface to work with different types of objects. It helps write flexible and reusable code.

When you want to treat different types of objects in the same way.
When you want to add new object types without changing existing code.
When you want to call the right function for an object automatically.
When you want to simplify complex code by using common interfaces.
When you want to design programs that can grow easily over time.
Syntax
C++
class Base {
public:
    virtual void show() {
        // base version
    }
};

class Derived : public Base {
public:
    void show() override {
        // derived version
    }
};

virtual keyword tells C++ to use polymorphism for that function.

Derived classes override the base class function to provide their own behavior.

Examples
Base class Animal has a virtual function sound(). Derived class Dog changes it to print "Bark".
C++
class Animal {
public:
    virtual void sound() {
        std::cout << "Some sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Bark" << std::endl;
    }
};
Pointer of base type Animal* points to a Dog object. Calling sound() runs the Dog version.
C++
Animal* pet = new Dog();
pet->sound();  // Calls Dog's sound() because of polymorphism
Sample Program

This program shows polymorphism by calling sound() on base class pointers that point to different derived objects. The right function runs automatically.

C++
#include <iostream>

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

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

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

int main() {
    Animal* pet1 = new Dog();
    Animal* pet2 = new Cat();

    pet1->sound();  // Calls Dog's sound
    pet2->sound();  // Calls Cat's sound

    delete pet1;
    delete pet2;
    return 0;
}
OutputSuccess
Important Notes

Without polymorphism, the base class function would always run, ignoring derived versions.

Polymorphism helps keep code easy to extend and maintain.

Summary

Polymorphism allows one interface to work with many object types.

It helps call the correct function automatically based on the object.

This makes code flexible, reusable, and easier to grow.