Search code examples
c++inheritancepolymorphismfunction-pointersstatic-polymorphism

C++ Polymorphic Static Changeable Child Function Pointer


I have a class A that is a child of class B, I need all children of class B to have a function pointer to a function for handling the class that is changeable by an external function in a different file after the classes have been compiled. All instances of class A should point to one function, and all instances of B should point to a function, but A and B should be able to point to different functions. How can I do this? I have tried a static function pointer and a private static function pointer but neither have worked.

class B{
    public:
    static void (* func)();
}
class A : public B{

}
class C : public B{

}
void funcA(){
    cout<<"A"<<endl;
}
void funcB(){
    cout<<"B"<<endl;
}
void funcC(){
    cout<<"C"<<endl;
}
void main(){
    B b=B();
    B b2=B();
    B a=A();
    B a2=A();
    B c=C();
    B c2=C();
    b.func=funcB;
    a.func=funcA;
    c.func=funcC;
    a.func();
    b.func();
    c.func();
    a2.func();
    b2.func();
    c2.func();
}

My desired output is

B
A
C
B
A
C

Solution

  • If you want all instances of a derived class to share the same function-pointer you need to put one function-pointer in each class.

    It's not clear from your question if you want polymorphic behaviour from the classes, but I assumed so in this answer. If you combine virtual functions and a static function pointer you can get the behavior your looking for.

    #include <iostream>
    
    using fptr = void (*)();
    
    class B {
        public:
        virtual void func() {
            bfunc();
        }
        static fptr bfunc;
    };
    fptr B::bfunc;
    
    class A : public B{
        public:
        void func() override {
            afunc();
        }
        static fptr afunc;
    };
    fptr A::afunc;
    
    class C : public B{
        public:
        void func() override {
            cfunc();
        }
        static fptr cfunc;
    };
    fptr C::cfunc;
    
    void funcA(){
        std::cout<<"A"<<std::endl;
    }
    void funcB(){
        std::cout<<"B"<<std::endl;
    }
    void funcC(){
        std::cout<<"C"<<std::endl;
    }
    
    int main(){
        B b=B();
        B b2=B();
        A a=A();
        A a2=A();
        C c=C();
        C c2=C();
        B::bfunc=funcB;
        A::afunc=funcA;
        C::cfunc=funcC;
        a.func();
        b.func();
        c.func();
        a2.func();
        b2.func();
        c2.func();
    
        B* c3 = new C;
        c3->func();
        delete c3;
    }