cpp-polimorfismo

What is and how to use polymorphism in C++

  • 2 min

Polymorphism is one of the fundamental principles of object-oriented programming (OOP), which allows objects to be treated as instances of their base class, while still retaining their own specific behavior.

If you want to learn more about object-oriented programming, here is the link to the Object-Oriented Programming Course.

Learn OOP, the most influential programming paradigm

Virtual Functions and Overriding

In C++, a virtual function is one that can be overridden in derived classes, modifying or extending its behavior with its own implementation.

To do this, they must be declared in the base class with the keyword virtual.

class Animal {
public:
    virtual void hacerSonido() const {
        cout << "The animal makes a sound." << endl;
    }
};
Copied!
class Dog : public Animal {
public:
    void hacerSonido() const override {
        cout << "The dog barks." << endl;
    }
};
Copied!
class Cat : public Animal {
public:
    void hacerSonido() const override {
        cout << "The cat meows." << endl;
    }
};
Copied!

In the previous example,

  • hacerSonido is a virtual function in the base class Animal.
  • Both Dog and Cat override this method to define their own sound.

Using Polymorphism

Now let’s see how polymorphism works. We create two instances of our classes Dog and Cat, but we store them in a variable of type Animal.

Now we call the hacerSonido method. What is going to happen? Will it output the message El animal hace un sonido, which is what is defined in Animal?

Animal* myAnimal = new Dog();
myAnimal->hacerSonido(); // Output: The dog barks.

myAnimal = new Cat();
myAnimal->hacerSonido(); // Output: The cat meows.
Copied!

No! Perro makes its sound, and Gato makes its own. That is, each instance executes the method overridden in the concrete class (Dog or Cat).

This is polymorphism in action. It allows hacerSonido to be executed according to the concrete type of the object we have at runtime (not according to the variable type definition).

Which is only logical. Even though we access the objects through a variable of type Animal, when executing the method, what we find depends on the object that is stored.