0
#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?

sajas
  • 1,599
  • 1
  • 17
  • 39

1 Answers1

2

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.

tmyklebu
  • 13,915
  • 3
  • 28
  • 57
  • Thanks for the reply. It's working the way i want it. But I didn't understand why it was giving me the error earlier. Since f is a public member why can't i access it in Handler? What was happening when i had written (b->*f)()? – sajas Jan 15 '13 at 07:59
  • 2
    @sajas: Member pointer syntax is always confusing. In `Handler`, the name of the member is `b->f`, just like any other member variable. (A longer version would be `function bf = b->f; b->*bf();`.) The `b->*` sequence says "call one of b's member functions" but the thing after the "*" must be named from `Handler`'s perspective, not `b`'s - that arrow doesn't "reach inside" `b`. – molbdnilo Jan 15 '13 at 08:33