Virtual function calls can be slow due to virtual calls requiring an extra indexed deference to the v-table, which can result in a data cache miss as well as an instruction cache miss... Not good for performance critical applications.
So I have been thinking of a way to overcome this performance issue of virtual functions yet still having some of the same functionality that virtual functions provide.
I am confident that this has been done before, but I devised a simple test that allows the base class to store a member function pointer that can be set by any the derived class. And when I call Foo() on any derived class, it will call the appropriate member function without having to traverse the v-table...
I am just wondering if this method is a viable replacement for the virtual-call paradigm, if so, why is it not more ubiquitous?
Thanks in advance for your time! :)
class BaseClass
{
protected:
    // member function pointer
    typedef void(BaseClass::*FooMemFuncPtr)();
    FooMemFuncPtr m_memfn_ptr_Foo;
    void FooBaseClass() 
    {
        printf("FooBaseClass() \n");
    }
public:
    BaseClass()
    {
        m_memfn_ptr_Foo = &BaseClass::FooBaseClass;
    }
    void Foo()
    {
        ((*this).*m_memfn_ptr_Foo)();
    }
};
class DerivedClass : public BaseClass
{
protected:
    void FooDeriveddClass()
    {
        printf("FooDeriveddClass() \n");
    }
public:
    DerivedClass() : BaseClass()
    {
        m_memfn_ptr_Foo = (FooMemFuncPtr)&DerivedClass::FooDeriveddClass;
    }
};
int main(int argc, _TCHAR* argv[])
{
    DerivedClass derived_inst;
    derived_inst.Foo(); // "FooDeriveddClass()"
    BaseClass base_inst;
    base_inst.Foo(); // "FooBaseClass()"
    BaseClass * derived_heap_inst = new DerivedClass;
    derived_heap_inst->Foo();
    return 0;
}
 
     
     
     
     
    