Hi All,

Can anybody help me to assign a base class function pointer in derived class constructor? I have got a compilation error while doing so. Please see the code below:

class Base
{
public:
	void (* fnptr) (void) ;
	void myvurtualfn()
	{
	}  	
};
class Derived:public Base
{
public:
	
	void myvurtualfn1()
	{
	}
	Derived()
	{	
                fnptr =this->myvurtualfn1(); //error C2440: '=' : cannot convert from 'void' to 'void (__cdecl *)(void)'
	}

};

Thanks in Adv,
Je

Edited 6 Years Ago by Nick Evan: Added code-tags

>fnptr =this->myvurtualfn1(); //error C2440: '=' : cannot convert from 'void' to 'void (__cdecl *)(void)'

  1. You're not taking the address of the member function, you're calling it.
  2. Pointers to member functions are not compatible with pointers to functions.

This might help with the syntax issues.

Hi Naure,
Thanks v much for your help.

I have modified the code as given below. Now the assignment of base class member function pointer is OK. Now I have an another problem in calling the function. it gives compilation error as "error C2065: 'fnptr' : undeclared identifier" Is it possible to call like that? Or is it a syntax error?

class Base
{
public:
    void ( Base :: *fnptr)(void) ;
    void myvurtualfn(void){}  
    Base()
    {
        fnptr = &Base::myvurtualfn;
        (this->*fnptr)();
    }
};

class Derived:public Base
{
public:

    void myvurtualfn(){}
    Derived()
    {
            fnptr = &Base :: myvurtualfn;
    }
};
void myoldfn(Base &b)
{   
    (b.*fnptr)();//error C2065: 'fnptr' : undeclared identifier
}

Thanks in advance,
Jeso

Edited 3 Years Ago by Nick Evan: Fixed formatting

The .* syntax only says what object you're applying the pointer to; you still need to do everything necessary to access the pointer itself:

(b.*b.fnptr)();

In your code, the compiler is looking for fnptr in the unadorned scopes, but fnptr is actually a member of Base, so you need to use the full name of b.fnptr .

Doing the double membership is awkward and can be confusing, so perhaps an intermediate local variable is a better solution:

void (Base::*p)() = b.fnptr;
(b.*p)();

Hi Naure,
My problem has gone.
Thanks very much for your help.

Best regards,
Jeso

This question has already been answered. Start a new discussion instead.