Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does C++ 'final' method annotation promise about the class design?

Tags:

c++

oop

c++11

I am aware what the final method annotation in C++ (since C++11) does from a language point-of-view.

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

Any class deriving from Locked can not override method anymore.

But what does it say about the API, the contract from an OOP point of view? As already asked for Java, what must I be aware of, as a class author of Locked, about the design of the whole class now, what do I promise?

For example: I could imagine that by annotating with final I am saying that "this methods behavior does not change". But what if I call other methods inside method()? If they can be overridden, how can I promise that? So, does annotating with final mean, I must not use other overridable methods inside that method, strictly speaking, from an OOP point-of-view? Or other design constraints?

like image 409
towi Avatar asked Aug 22 '14 09:08

towi


1 Answers

Usually you should be using the final keyword to provide user with the certainty that no overwritten behavior for this function will occur for security reasons or any other requirements that make you want to restrict the class function to be final.

If you are using any other methods they should also be marked as final unless for instance the field on which they are operating are private ( you can imagine some scenarios in which default behavior modifies private fields but you can allow overwritten function to do something else as well).

The keyword itself ONLY restricts the function to be overwritten it wont magically know what does it really mean for the function not to change with classes extending base.

#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"

like image 65
cerkiewny Avatar answered Oct 11 '22 17:10

cerkiewny