Search code examples
c++pointersvirtual

Invoke derived class function via pointer to base class function


I want to invoke some method on child class using its interface, but I want to use pointers to interface methods.

Something like this:

#include <iostream>

using namespace std;


class IA
{
    public:
    virtual void f() = 0;
};

class A : public IA
{
    public:

    virtual void f()
    {
        cout<<"A::f()"<<endl;
    }   
};

int main()
{   
    typedef void (IA::*Func)();

    Func func;
    func = &IA::f;

    IA *a = new A();

    a.*(func);

    delete a;

    return 0;
}

Do you know how to solve this ?


Solution

  • The invocation should be:

    (a->*func)()
    

    (This binds the member function pointer to a then invokes the member function.)

    Otherwise, your code is correct.