Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
when i am executing following code:
class Derived;
typedef void (Derived::*callbackf)() ;

class Base;
typedef map<Base*, callbackf*> MYLIST;
class Base
{
public:
	Base(void){};
	MYLIST mylist;
	void Attach(Base* p, callbackf*){mylist[p] = voidpt;};
	~Base(void){};
};

class Derived :	public Base
{
public:
	Derived(void)
            {
                callbackf ponLocoMoving = &Derived::onLocoMoving;
        	Attach(this, &ponLocoMoving);};
            }
	void onMoving(){};
	~Derived(void){};
};
int _tmain(int argc, _TCHAR* argv[])
{
	
	Base *b;
	b= new Derived();

	MYLIST::iterator itr;
	itr = b->mylist.begin();

	for (itr = b->mylist.begin(); itr != b->mylist.end(); itr++)
	{
		Base* clsOb = (*itr).first;
		callbackf fn = b->mylist[(*itr).first];
		(*clsOb.*fn)();
	}
	return 0;
}
I am getting two errors: 'initializing' : cannot convert from 'void *' to 'callbackf' 'newline' : cannot convert from 'Base *__w64 ' to 'Derived *__w64 ' '.*' : cannot dereference a 'callbackf' on a 'Base'
Posted
Updated 20-Nov-09 23:08pm
v2

I am getting two errors: 'initializing' : cannot convert from 'void *' to 'callbackf' 'newline' : cannot convert from 'Base *__w64 ' to 'Derived *__w64 ' '.*' : cannot dereference a 'callbackf' on a 'Base'

The first problem :

>> I am getting two errors: 'initializing' : cannot convert from 'void *' to 'callbackf'

... is related to your type definition of MYLIST :

typedef map<Base*, callbackf*> MYLIST;

You need not declare the mapped object type as "callbackf*". callbackf is already a pointer and so MYLIST can simply be stated as :

typedef map<Base*, callbackf> MYLIST;

You have to make other modifications to your overall code if you do decide to make the above change.

The second problem :

>> 'newline' : cannot convert from 'Base *__w64 ' to 'Derived *__w64 ' '.*' : cannot dereference a 'callbackf' on a 'Base'

...is known as contravariance. There is a predefined conversion from a pointer to a member function of a base class to a pointer to a member function of a derived class but not the reverse.

This is because a member function of a base class will only be able to access member data and/or member functions of the base class only. But the member function of a derived class may access the member data/functions of the derived class which will not be defined in the base class.

Because of this, C++ will not allow the following (found in your code) to be compiled :

    (*clsOb.*fn)();

where clsOb is a pointer to Base. This is because fn is typed as a member function of class "Derived" and not "Base".

- Bio.

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900