C++ forbid overwriting a virtual function
I use a class A from a library and want to add some functionality to it via an own class B. The user of c开发者_如何转开发lass B should derive from it as if he would derive from class A.
class A {
public:
virtual void func1()=0;
virtual void func2()=0;
...
}
class B: public A {
public:
virtual void func1() {...}
}
So if someone creates a class C deriving from B, he should have to implement func2:
class C: public B {
public:
virtual void func2() {...}
}
It is very important for my application, that class C doesn't overwrite func1, eliminating B::func1().
Is there a way to forbid overwriting this virtual function for all child classes of B? If not in plain C++, is there something in boost MPL that throws a compiler error, when this function is overwritten?
No, that's not possible in the current edition of C++, aka C++03. The upcoming C++11 standard will include the contextual keyword final
which will make this possible:
// C++11 only: indicates that the function cannot be overridden in a subclass
virtual void MemberFunction() final { ... }
The Microsoft Visual C++ compiler also includes the keyword sealed
, as an extension, which functions similarly to the C++11 keyword final
, but this only works with Microsoft's compiler.
Not in C++03, but C++0x provides the special "final" identifier to prohibit this:
http://en.wikipedia.org/wiki/C++0x#Explicit_overrides_and_final
No. In C++03, you cannot stop derived classes from overriding1 virtual function(s) of base classes. However, base classes can force the derived (non-abstract) classes to provide implementation for virtual functions (in which case, the virtual functions are actually pure virtual functions).
1. The correct terminology is override, not overwrite.
精彩评论