Always call the virtual function of a superclass when a child override is called

I have this structure:

class A { public: virtual void func(int a) { cout << "System is initiated correctly." << a; } }; class B : public A { public: virtual void func(int a) override { A::func(a); cout << "This particular system is initiated correctly too" << a; } }; 

Now in 95% of cases when I am overloaded from A, I override func , and in 100% of cases I have to call A::func(); before doing anything else? How can I prevent this from being recorded manually. Sometimes I even forgot to call A::func(); in the child class A::func(); and get runtime errors, throws, etc.

+5
source share
1 answer

What about the NVI template ?

 class A { public: void func(int a) { cout << "System is initiated correctly." << a; do_func(a); } private: virtual void do_func(int a) {} }; class B : public A { private: virtual void do_func(int a) override { cout << "This particular system is initiated correctly too" << a; } }; 
+16
source

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


All Articles