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

23,191

Solution 1

If you make the method non-virtual, derived classes cannot override the method. However, in C++03 a class cannot override a method from a base class, and also prevent further derived classes from overriding the same method. Once the method is virtual, it stays virtual.

Solution 2

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()’

Solution 3

Don't make it virtual.

This won't prevent deriving from your class and hiding the function (by providing another member function with the same name). However, if your class is not meant to be derived anyway (no virtual destructor, no virtual member functions), that shouldn't be an issue.

Solution 4

well if you want to keep it public, dont declare it virtual.

EDIT: Srikanth commented wondering about overriding a private member function in a derived class.

class A
{
public:
    virtual ~A(){};
    void test()
    {
        foo();
    };
private:
    virtual void foo()
    {
        std::cout << "A";   
    };
};


class B : public A
{
public:
    virtual void foo()
    {
        std::cout << "B";   
    };
};


void test()
{
    B b;
    A& a = b;

    a.test(); // this calls the derived B::foo()

    return 0;
}`
Share:
23,191
sriks
Author by

sriks

Updated on July 09, 2022

Comments

  • sriks
    sriks almost 2 years

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