implement a virtual method from the base class as

2019-06-08 06:45发布

问题:

I have an abstract base class with a virtual method. In the derived class, this method is implemented. However, I want the function in the derived class as a static method in order to be able to call the function without instantiating an object of that class.

class Base 
{
   virtual double Foo(double rParam) const;
};

class Derived1 : public Base
{
   static double Foo(double rParam);
};

class Derived2 : public Base
{
   static double Foo(double rParam);
};

Essentially, Derived1 and Derived2 provide different implementations of a static function (that do not depend on object data), but I want those functions to be virtual in order to be able to call those functions in other functions of the base class. The only solution I see right now is to implement two member functions in the derived class, one being the virtual function from the base class, and the other one (with a different name) being a static function. In order to prevent doubling the source code, the virtual function could then directly call the static function (could be inlined). Any other solutions?

class Derived : public Base
{
   double Foo(double rParam)const
   {
       return FooStatic(rParam);
   }

   inline static double FooStatic(double rParam);
};

回答1:

I do think that the FooStatic approach you have is the best way to go about it, in terms of adhering to good OO practice. Essentially, your non-static Foo overrides work like function pointers into your static versions.

(Emphasis on "work like": you can't actually use function pointers directly, since your override for Foo has to throw away the reference to this before invoking FooStatic.)



回答2:

It would not make sense to make a virtual method static. Virtual means that you choose which implementation to run based on the type of an object. In a static context you have no object.

EDIT: While the first example will compile, it will not do what you expect it to do. The static methods will not override the base implementation, but rather hide it, meaning that the static methods will never be called instead of that of the base class. The second example is fine though, I cannot see any problem with it.