Prevent inheritance class from overriding the base class virtual function

The situation is as follows.

class Interface { public: virtual void foo() = 0; } class MyClass : Interface { public: virtual void bar() = 0; private: void foo() { //Some private work and checks. bar(); }; } 

I want my user to create a class that inherits from MyClass, and they will have to implement bar() .
But how can I argue that they would not override foo() ? because it is important for me to use my foo() .

+6
source share
2 answers

In C ++ 11, you can mark a method as final to prevent it from being overridden:

 class MyClass : Interface { public: virtual void bar() = 0; private: void foo() final { //Some private work and checks. bar(); }; } 
+13
source

According to another answer, you can use the final keyword in C ++ 11 (such an object is similar to the Java final keyword).

For C ++ 03 code, you can use the CRTP mechanism (if you can change the definition of Interface )

 template<typename Derived> class Interface { public: void foo() // not 'virtual' { static_cast<Derived*>(this)->foo(); } } class MyClass : public Interface<MyClass> { public: virtual void bar() = 0; private: void foo() { //Some private work and checks. bar(); }; } 

So, now you remove virtual ness foo() , and the binding will happen at compile time. Remember that CRTP comes with its own restriction, so whether you use it or not is up to you.

+6
source

Source: https://habr.com/ru/post/905442/


All Articles