1
votes

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);
};
2
If Foo is marked as virtual, it means it depends on the runtime type of the object, so it can't not be coupled with an instance of a class.Luchian Grigore
The situation is a bit more tricky. As a simplified example, assume we have a base class that requires a function foo. In Derived1, this is a linear function , so foo(x)=x and in Derived2 foo(x)=x^2, so both functions do not depend on the object data. However, I want the function to be virtual in the base class in order to be able to call this function from another function in the base class. There are also other data members in the derived class, however, this is not important for the current example with the static/virtual methods.Ferdi

2 Answers

0
votes

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

0
votes

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.