1

For example: I have an implementation (say doSomething()) in Base class.

I want all the Derived classes to use only this implementation, and not to override the base class implementation.

How can I force this behavior in C++?

4

3 回答 3

3

If you only want to implement it in the base class, then don't declare it virtual, and it can't be overridden at all.

In C++11 you can declare an override final in a similar way to Java:

virtual void doSomething() final;
                           ^^^^^

In C++03 and earlier, you can't; that's why it was added to C++11.

于 2012-04-06T09:30:41.633 回答
2

In C++11 declare the method as final.

In C++03, You don't have the in-built(language provided) functionality but you can do the following:

  • Not Declare the method as virtual in the Base class.
  • Don't add any same named methods in Derived classes.
  • Doccument the purpose approriately.

#1: Ensures Derived classes cannot override the particular method. The same method has to be called for all objects(Base or Derived), Since the method cannot be overridden.

#2: This ensures there is no Function Hiding, and any possibility of hiding the Base class method.

#3: This warns users of your class, of the rationale and the purpose.

于 2012-04-06T09:32:40.027 回答
2

If the final function is in the base class of the class hierarchy, simply do not declare it virtual. Then it can't be overridden.

If the final function is not in the base class (i.e. is a virtual function), you can use the final identifier from C++11 to declare a function final:

struct Base2 {
    virtual void f() final;
};
于 2012-04-06T09:33:27.953 回答