Ex3.1: Polymorphism - miguelneto1123/CES-22 GitHub Wiki

Polymorphism encourages the programmer to think of methods before using the superclasses and overriding them later. It also permits this kind of code:

Animal *v[3];

v[0] = new Lobo();
v[1] = new Girafa();
v[2] = new Humano();

for (int i = 0; i < 3; i++){
    v[i]->comer("planta");
    v[i]->comer("carne");
}

This will call the subclass method for each of the vector elements, producing the following output:

O lobo nao comeu planta
O lobo comeu carne
A girafa comeu planta
A girafa nao comeu carne
O humano comeu planta
O humano comeu carne

Even though the vector elements are of type Animal, they can call the overriden method from its subclasses because it also has the original method, with the same name. A situation where this would be useful is when you design a GUI that needs a draw() method. Even if you have 35 specific types of blocks to draw, you can call a iterative draw() into all Block elements, which will work for the specific Block classes, like SolidBlock, TranslucidBlock, InteractiveBlock and so on.