C++ - Keyword - virtual

The virtual keyword is used in different ways in C++.

The most common way to use it is before a destructor.
Indeed, with this virtual keyword we can specified that the children of a class will be deleted before its parent.

Let's see it with a tutorial.

1. virtual before a destructor

In this example, I created two classes, a Parent and a Child. So Child inherits from Parent.

The headers:

// parent.hh

class Parent {
public:
    Parent();
    ~Parent();
};

// child.hh

class Child: public Parent {
public:
    Child();
    ~Child();
};

Then the sources:

// parent.cpp

#include "parent.hh"
#include <iostream>

Parent::Parent() {
    std::cout << "Parent created." << std::endl;
}

Parent::~Parent() {
    std::cout << "Parent deleted." << std::endl;
}

// child.cpp

#include "child.hh"
#include <iostream>

Child::Child() {
    std::cout << "Child created." << std::endl;
}

Child::~Child() {
    std::cout << "Child deleted." << std::endl;
}

And the main.cpp:

#include "parent.hh"
#include "child.hh"

int    main() {

    Parent *human = new Child;

    delete human;

    return 0;
}

Now let's compile it and see the famous result:

Parent created.
Child created.
Parent deleted.

And this case, the child instance can not be deleted anymore!

How to resolve this problem?

With the virtual keyword of course!

I just add virtual before each destructor in the respective classes.
The sources stay the same:

// parent.hh

class Parent {
public:
    Parent();
    virtual ~Parent();
};

// child.hh

class Child: public Parent {
public:
    Child();
    virtual ~Child();
};

Let's compile:

Parent created.
Child created.
Child deleted.
Parent deleted.

Now the child is deleted.

The virtual keyword transform a function into a method.
This is important, because a function is interpreted during the compilation and a method during the execution.

We can also notice that if we test this example with:

 Child *human = new Child;

instead of

 Parent *human = new Child;

we will be able to delete the child without the virtual keyword.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.