When you can use the final
specifier for virtual methods (introduced with C++11), you can do it. Let me quote my favorite doc site:
When used in a virtual function declaration, final specifies that the function may not be overridden by derived classes.
Adapted to your example that'd be like:
class Base {
public:
virtual bool someGuaranteedResult() final { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
When compiled:
$ g++ test.cc -std=c++11
test.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’
test.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’
When you are working with a Microsoft compiler, also have a look at the sealed
keyword.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…