DEV Community

Cover image for Polymorphism in C++ - Explained in Simple Words
Aliza Kanwal
Aliza Kanwal

Posted on

Polymorphism in C++ - Explained in Simple Words

Polymorphism means "many forms". In C++, it means one function name can work in many different ways.

Think of it like this: Every animal makes a sound, but the sound is different.
Cat says Meow, Dog says Bark, Bird says Chirp. The function name is same - makeSound() - but the result is different. This is Polymorphism!

Let's see a simple example:


cpp
#include <iostream>
using namespace std;

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

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

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

int main() {
    Animal* a1 = new Cat();
    Animal* a2 = new Dog();

    a1->makeSound();
    a2->makeSound();
    return 0;
}
Output:
Meow!
Bark!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)