What is polymorphism give an example

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. It enables you to write more flexible and reusable code by allowing different classes to provide their own implementations of methods with the same name, typically through method overriding.

There are two main types of polymorphism in object-oriented programming:

  1. Compile-Time Polymorphism (Static Binding): Also known as method overloading, it occurs at compile time. In this case, the appropriate method to be called is determined at compile time based on the method signature (name and parameter types).
  2. Run-Time Polymorphism (Dynamic Binding): Also known as method overriding, it occurs at runtime. The decision about which method to call is made at runtime based on the actual type of the object.

Here’s an example of run-time polymorphism using method overriding in C++:

 

#include <iostream>

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

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

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

int main() {
    Animal* myAnimal;

    Dog myDog;
    Cat myCat;

    myAnimal = &myDog;
    myAnimal->makeSound(); // Calls Dog's makeSound method

    myAnimal = &myCat;
    myAnimal->makeSound(); // Calls Cat's makeSound method

    return 0;
}
  • We define a base class Animal with a virtual method makeSound().
  • We create two derived classes, Dog and Cat, which override the makeSound() method with their own implementations.
  • In the main() function, we create instances of Dog and Cat.
  • We use a pointer to the base class Animal to point to instances of Dog and Cat.
  • When we call makeSound() through the pointer, it calls the appropriate method for the actual object’s type, demonstrating run-time polymorphism.

The ability to treat objects of different derived classes as objects of a common base class and have their methods behave according to their actual types is a powerful feature of polymorphism in object-oriented programming.

Leave a comment