Language: EN

cpp-polimorfismo

What is and how to use polymorphism in C++

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 preserving their own specific behavior.

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

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 virtual keyword.

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

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 Dog and Cat classes, but we store them in a variable of type Animal.

Now we call the hacerSonido method. What is going to happen? Will the message The animal makes a sound, which is what is defined in Animal, be displayed?

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

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

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

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

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