Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a method from being overridden in derived class? [duplicate]

How can I enforce that a base class method is not being overridden by a derived class?

like image 583
sriks Avatar asked Dec 16 '10 21:12

sriks


1 Answers

If you are able to use the final specifier from C++11 you can prevent derived classes from override that method. (Microsoft compilers appear to support the similar sealed with similar semantics.)

Here's an example:

#include <iostream>

struct base {
    // To derived class' developers: Thou shalt not override this method
    virtual void work() final {
        pre_work();
        do_work();
        post_work();
    }
    virtual void pre_work() {};
    virtual void do_work() = 0;
    virtual void post_work() {};
};

struct derived : public base {
    // this should trigger an error:
    void work() {
        std::cout << "doing derived work\n";
    }
    void do_work() {
        std::cout << "doing something really very important\n";
    }
};

int main() {
    derived d;
    d.work();
    base& b = d;
    b.work();
}

Here's what I get when I try to compile it:

$ g++ test.cc -std=c++11
test.cc:17:14: error: virtual function ‘virtual void derived::work()’
test.cc:5:22: error: overriding final function ‘virtual void base::work()’
like image 148
moooeeeep Avatar answered Oct 02 '22 13:10

moooeeeep