How to prevent a method from being overridden in derived class?
If you are able to use the final
specifier from C++11 you can prevent derived classes from override that method. (Microsoft compilers appear to support the similar sealed
with similar semantics.)
Here's an example:
#include <iostream>
struct base {
// To derived class' developers: Thou shalt not override this method
virtual void work() final {
pre_work();
do_work();
post_work();
}
virtual void pre_work() {};
virtual void do_work() = 0;
virtual void post_work() {};
};
struct derived : public base {
// this should trigger an error:
void work() {
std::cout << "doing derived work\n";
}
void do_work() {
std::cout << "doing something really very important\n";
}
};
int main() {
derived d;
d.work();
base& b = d;
b.work();
}
Here's what I get when I try to compile it:
$ g++ test.cc -std=c++11
test.cc:17:14: error: virtual function ‘virtual void derived::work()’
test.cc:5:22: error: overriding final function ‘virtual void base::work()’
If you make the method non-virtual, derived classes cannot override the method. However, in C++03 a class cannot override a method from a base class, and also prevent further derived classes from overriding the same method. Once the method is virtual, it stays virtual.