sajas
sajas

Reputation: 1599

Calling a member function using function pointers from another class's instance

#include<iostream>
#include<conio.h>
using namespace std;
class Base;
typedef void (Base::*function)();
class Base
{
public:
    function f;
    Base()
    {
        cout<<"Base Class constructor"<<endl;
    }
    virtual void g()=0;
    virtual void h()=0;
};
class Der:public Base
{
public:
    Der():Base()
    {
        cout<<"Derived Class Constructor"<<endl;
        f=(function)(&Der::g);
    }
    void g()
    {
        cout<<endl;
        cout<<"Function g in Derived class"<<endl;
    }
    void h()
    {
        cout<<"Function h in Derived class"<<endl;
    }
};
class Handler
{
    Base *b;
public:
    Handler(Base *base):b(base)
    {
    }
    void CallFunction()
    {
        cout<<"CallFunction in Handler"<<endl;
        (b->*f)();
    }
};
int main()
{
    Base *b =new Der();
    Handler h(b);
    h.CallFunction();
    getch();
}

I am getting an error while trying to call a member function in a derived class using function pointer declared in the base class. The function pointer is declared public and is actually used by another class Handler. I have used an unsafe typecast in this code. (function)(&Der::g). Is there any way to avoid it?

Upvotes: 0

Views: 692

Answers (1)

tmyklebu
tmyklebu

Reputation: 14225

f doesn't appear to be in scope in Handler::CallFunction. I'm guessing you meant to call the b->f using b as this, as it (b->*(b->f))(). When I make this change, your code compiles and prints out something sane.

Upvotes: 2

Related Questions