override

Correct Overriding …

Here is a correct example …

#include <iostream>
using namespace std;

class Base
{
public:
    virtual ~Base() {}

    virtual void method() const
    {
        cout << "Base::method" << endl;
    }
};

class Derived : public Base
{
public:
    virtual void method() const
    {
        cout << "Derived::method" << endl;
    }
};

int main()
{
    Derived d;
    Base* b = &d;
    b->method();
    return 0;
}
$ ./c++11-override-ok
Derived::method

Important

Both Base::method() and Derived::method() have exact same signature

… Is Very Hard

For example, one could accidentally omit the const

  • ⟶ completely different, new, method!

  • ⟶ base class method called (when accessed via base class pointer)

#include <iostream>
using namespace std;

class Base
{
public:
    virtual ~Base() {}

    virtual void method() const
    {
        cout << "Base::method" << endl;
    }
};

class Derived : public Base
{
public:
    virtual void method()
    {
        cout << "Derived::method" << endl;
    }
};

int main()
{
    Derived d;
    Base* b = &d;
    b->method();
    return 0;
}
$ ./c++11-override-omit-const
Base::method

More Problems Arise

  • Accidentally omitting (or adding) const

  • Adding parameters

  • Changing parameter types

  • Refactoring: renaming base class (or interface) methods

  • In any case …

    • ⟶ Have to find out all implementations

    • ⟶ Might not even be in the same code base (plugins?)

Solution: override

#include <iostream>
using namespace std;

class Base
{
public:
    virtual ~Base() {}

    virtual void method() const
    {
        cout << "Base::method" << endl;
    }
};

class Derived : public Base
{
public:
    virtual void method() override
    {
        cout << "Derived::method" << endl;
    }
};

int main()
{
    Derived d;
    Base* b = &d;
    b->method();
    return 0;
}
code/c++11-override-keyword.cpp:18:18: error: ‘virtual void Derived::method()’ marked ‘override’, but does not override
   18 |     virtual void method() override
      |                  ^~~~~~