Category Archives: C++



Virtual functions in C++

In object-oriented programming we find the concept of polymorphism. It is the ability for different derived classes from the same superclass, use the same function differently.

Polymorphism in C++ is implemented with the help of virtual functions.

Better with an example.

We have two classes:

1
2
3
4
5
6
7
8
9
10
11
class Animal
{
    public:
        void eat() { std::cout << "I eat generic food"; }
}
 
class Cat : public Animal
{
    public:
        void eat() { std::cout << "I eat cat food"; }
}

We have this in main function:

1
2
3
4
5
Animal *animal = new Animal;
Cat *cat = new Cat;
 
animal->eat(); // Prints: "I eat generic food"
cat->eat();    // Prints: "I eat cat food"

Perfect, in this case we do not need virtual functions and everything works as expected.

But if for any reason we need to call the eat() function from an intermediate function:

1
2
// We can put this function at the beginning of our main.cpp file
void oneFunction(Animal *animal) { animal->eat(); }

Change our main function:

1
2
3
4
5
Animal *animal = new Animal;
Cat *cat = new Cat;
 
oneFunction(animal) // Prints: "I eat generic food"
oneFunction(cat)    // Prints: "I eat generic food"

As we can see, in this case always calls the eat() function of the superclass and not of the child class (Cat).

The solution is to convert the eat() function in a virtual function:

1
2
3
4
5
class Animal
{
    public:
        virtual void eat() { std::cout << "I eat cat food"; }
}

In main function:

1
2
oneFunction(animal) // Prints: "I eat generic food"
oneFunction(cat)    // Prints: "I eat cat food"

Although not necessary, I like indicate in the child class the virtual function too. This way, if we have a class that inherits from a superclass of another programmer, we know at a glance what are the overridden functions.

Therefore, this is our Cat class:

1
2
3
4
5
class Cat : public Animal
{
    public:
        virtual void eat() { std::cout << "I eat cat food"; }
}