Search code examples
c++inheritancestatic

How can I avoid calling a static function (and call a base member function instead)?


I have a static instance (previously called singleton, but commenters were taking issue with that) of a class which derives from a base class. So far, so good.

Derived has a static function fun, while Base has a member function fun (don't ask). Obviously, calling instance->fun() in Derived::fun() creates an infinite recursion ending in a stack overflow.

I managed to avoid that by calling ((Base*)instance)->fun() instead:

struct Base {
    void fun() { /* ... */ }
};

struct Derived;

static Derived * instance = nullptr;

struct Derived : Base {
    static void fun() {
        // stack overflow!
        // instance->fun();

        // works!
        ((Base*)instance)->fun();
    }
};

int main() {
    instance = new Derived();
    Derived::fun();
}

Is there a better way to avoid calling the static function defined in Derived?


Solution

  • You can call the function instance->Base::fun().