Search code examples
c++polymorphismstatic-methodsnon-static

static method with polymorphism in c++


I have a weird issue using polymorphism. I have a base class that implements a static method. This method must be static for various reasons. The base class also has a pure virtual method run() that gets implemented by all the extended classes. I need to be able to call run() from the static class.

The problem, of course, is that the static class doesn't have a this pointer. This method can be passed in a void * parameter. I have been trying to come up with a clever way to pass the run method into it, but nothing has worked so far. have also tried passing this into it. The problem with this is that I would then have to instantiate it, which requires knowledge of the extended class. This defeats the whole purpose of the polymorphism.

Any ideas on how to go about this?


Solution

  • Don't pass it as a void* pointer, pass it as a pointer (or reference) to the base class:

    class BaseClass
    {
    public:
      static void something(BaseClass* self) { self->foo(); }
      virtual void foo() = 0;  
    };