Is it possible to have a derived class that inherits the final function, but creates the same function (does not override)?

I have a problem with the final function. I want to “stop” polymorphism in a class, but I still want to generate the same function in a derived class.

Something like that:

 class Base{ protected: int _x, _y; public: Base(int x = 0, int y = 0) : _x(x), _y(y){}; int x() const { return _x; } int y() const { return _y; } virtual void print()const{ cout << _x*_y << endl; } }; class Derived : public Base{ public: Derived(int x = 0, int y = 0) : Base(x, y){} void print()const final { cout << _x*_y / 2.0 << endl; } // final inheritance }; class NonFinal : public Derived{ void print()const{ cout << "apparently im not the last..." << endl } // here i want a new function. not overriding the final function from Derived class }; 
+5
source share
2 answers

Sorry, but it is not possible to create a function in a derived class when a function with the same name exists as final in the base class. You will need to rethink your design.

The problem is that declaring a function in a derived class with the same name as the function in the base class is seen as an attempt to override whether the override keyword is present (for historical reasons, I suppose). Therefore, you cannot “disable” the override.

Here's the corresponding standard quote:

§ 10.3 / 4 [class.virtual]

If the virtual function f in some class B marked with the virt final specifier and in the class D derived from B , the function D::f overrides B::f , the program is poorly formed. [Example:

 struct B { virtual void f() const final; }; struct D : B { void f() const; // error: D::f attempts to override final B::f }; 

-end

+2
source

I think this is an experimental question, since in fact you should rethink what you do when you need to “redefine the final function” (it sounds contradictory, right?).

But you can enter a "dummy" parameter, i.e. void NonFinal::print(int test=0)const , which allows the compiler to treat the member function as another. Not sure if this solves your "problem"; but at least he introduces a function with the same name that you can still call without passing an argument and which is separate from the Derived and Base tags.

 class NonFinal : public Derived{ public: void print(int test=0)const{ cout << "apparently im not the last..." << endl; } }; int main() { Base b (10,10); Derived d (20,20); NonFinal nf; Base *bPtr = &d; bPtr->print(); // gives 200 bPtr = &nf; // gives 0 bPtr->print(); nf.print(); // gives "apparantly..." } 
+2
source

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


All Articles