piotrek
piotrek

Reputation: 1363

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 ?

Upvotes: 0

Views: 100

Answers (1)

James McNellis
James McNellis

Reputation: 355049

The invocation should be:

(a->*func)()

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

Otherwise, your code is correct.

Upvotes: 3

Related Questions