6

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

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94

2 Answers2

13

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();
    };
}
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Thanks, you lead me to the right direction. but in C++11V1.0 `final` was changed into `sealed`. – Roee Gavirel Jan 08 '12 at 12:02
  • 5
    Read [this question](http://stackoverflow.com/questions/7026462). `sealed` is microsoft-specific. `final` is defined in §7.6.4 [dcl.attr.final] of the C++11-standard. – Björn Pollex Jan 08 '12 at 20:13
6

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336