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()
.
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();
};
}
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 virtual
ness 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With