On the face of it this code looks sound; indeed it will compile with no errors or warnings. However, when it runs the Base version of op() will be executed!
The reason? Derived’s version of op() is not actually an override of Base::op since int and long are considered different types (it’s actually a conversion between an int and a long, not a promotion)
The compiler is more than happy to let you overload functions in the Derived class interface; but in order to call the overload you would need to (dynamic) cast the Base class object in usePolymorphicObject().
In C++11 the override specifier is a compile-time check to ensure you are, in fact, overriding a base class method, rather than simply overloading it.
In some cases you want to make a virtual function a ‘leaf’ function – that is, no derived class can override the method. The final specifier provides a compile-time check for this:
Can’t wait? Download the full set of articles as a PDF, here.
To learn more about Feabhas’ Modern C++ training courses, click here.
Latest posts by Glennan Carnie (see all)
- Your handy cut-out-and-keep guide to std::forward and std::move - April 26, 2018
- Setting up Sublime Text to build your project - April 12, 2018
- “May Not Meet Developer Expectations” #77 - February 15, 2018