Explicit virtual overrides
Use case
Catch typos when overriding virtual functions.
Explanation
override tells the compiler “we intend to override a base class function”. If we misspell the function name or get the signature wrong, we get a compile error (instead of silently creating a new function that never gets called).
Code
#include <iostream>
struct Analyzer {
virtual void analyze() { std::cout << "Running base analyzer.\n"; }
};
struct MachOAnalyzer : Analyzer {
void analyze() override { std::cout << "Running MachO analyzer.\n"; }
// member function declared with 'override' does not override a base class member
// void analize() override {}
};
int main() {
MachOAnalyzer m;
m.analyze();
return 0;
}
Output
$ ./src/c++11/build/explicit-virtual-overrides
Running MachO analyzer.