10.2 Virtual functions

10.2.1 Use the override special identifier when overriding a virtual function

The override special identifier is a directive to the compiler to check that the function is overriding a base class member. This will ensure that a change in the signature of the virtual function will generate a compiler error.

#include <cstdint>
   
class A {
public:
virtual void f(int64_t);
};
          
class B : public A {
public:
void f(int32_t) override;   // @@+ Compliant: Compile Error +@@
};

Note:The following was considered good C++ ’03 style:

#include <cstdint>
   
class A {
public:
virtual void f(int32_t);
};
          
class B : public A {
public:
virtual void f(int32_t);   // @@- Non-Compliant -@@
};
   
void f(A & a)
{
a.f(0);                // Results in (*@\color{blue}{B::f}@*) being called
}

However, this provided no guarantees and no additional checking by the compiler if the function signature was changed.

#include <cstdint>
   
class A {
public:
virtual void f(int64_t);
};
          
class B : public A {
public:
virtual void f(int32_t);   // @@- Non-Compliant -@@
};
   
void f(A & a)
{
a.f(0);                // Results in (*@\color{red}{A::f}@*) being called!!!!
}

References

  • HIC++ v3.3 – 3.3.16

Click here for references