I use a class A from a library and want to add some functionality to it via an own class B. The user of class 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.