Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent inheritor class from overriding virtual function of base class [duplicate]

The situation is like this.

class Interface
{
public:
    virtual void foo() = 0;
}

class MyClass : Interface
{
public:
    virtual void bar() = 0;
private:
    void foo()
    {
        //Some private work and checks.
        bar();
    };
}

I want that my user will create a class which inherit from MyClass, and they will have to implement there bar().
But how can I enfoce they wouldn't override foo()? because it's important to me to use my foo().

like image 864
Roee Gavirel Avatar asked Jan 08 '12 11:01

Roee Gavirel


2 Answers

In C++11 you can mark the method as final to prevent it from being overriden:

class MyClass : Interface
{
public:
    virtual void bar() = 0;
private:
    void foo() final
    {
        //Some private work and checks.
        bar();
    };
}
like image 106
Björn Pollex Avatar answered Sep 22 '22 15:09

Björn Pollex


As per other answer, you can use final keyword in C++11 (such facility is similar to Java's final keyword).

For C++03 code, you can use CRTP mechanism (provided if you can change the definition of Interface)

template<typename Derived>
class Interface
{
public:
  void foo()  // not 'virtual'
  {
    static_cast<Derived*>(this)->foo();
  }
}

class MyClass : public Interface<MyClass>
{
public:
    virtual void bar() = 0;
private:
    void foo()
    {
        //Some private work and checks.
        bar();
    };
}

So now you have remove the virtualness of the foo() and the binding will happen at compile time. Remember that CRTP comes with its own limitation, so whether to use it or not is up to you.

like image 22
iammilind Avatar answered Sep 23 '22 15:09

iammilind