What is the annotation for C ++ 'final' about class design?

I know that the annotation of the final method in C ++ (since C ++ 11) is done in terms of language.

 class Base { virtual void method(); }; class Locked : public Base { virtual void method() final; }; 

Any class derived from Locked can no longer override method .

But what does he say about the API, about the contract in terms of OOP? As Java has already said , what should I know as the author of the Locked class about the design of the entire class now , what do I promise?

For example: I could imagine that, annotating with final , I say that "this behavior of the methods does not change." But what if I call other methods inside method() ? If they can be redefined, how can I promise this? So, does the final value comment, should I not use other overridable methods inside this method, strictly speaking, from the point of view of OOP? Or other design limitations?

+5
source share
2 answers

Normally, you should use the final keyword to give the user confidence that no overwritten actions for this function will arise for security reasons or any other requirements that make you want to limit the class function to final.

If you use any other methods, they should also be marked as final unless the field in which they work is private (you can imagine some scenarios in which the default behavior modifies the private fields, but you can allow rewritable function is something else).

The keyword ONLY restricts the function to be overwritten, usually does not know what this means, because the function should not change with the extension of the database.

 #include <iostream> using namespace std; class foo{ public: virtual int bar() final{ foobar(); } virtual void foobar(){cout << "blah";} }; class baz : public foo{ public: void foobar() override { cout << " not blah"; } }; int main(){ baz * a = new baz(); a->bar(); } 

For example, this code will print "not Blah"

+5
source

From the point of view of OO theory (see LSP ), an overridden method in a derived class should not violate any contract of this method set to the base class. That is, from the point of view of the user, ideally there is no difference whether the method is redefined anywhere or not. Thus, it looks like optimization opportunity for the compiler or a hint for programmers who might want to subclass further.

0
source

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


All Articles