Archived

This topic is now archived and is closed to further replies.

ferceg

function parameters

Recommended Posts

Hi! I have two classes: test1 and test2. A function in test1 takes a function as parameter:
  
typedef void (funcptr)(int, int);

class test1
{
	public:

	void Init(funcptr *func);
};

//test2:


class test2
{
	public:

	void func(int a, int b);
	void Init();
};

void test2::Init()
{
	test1		qqq;

	qqq.Init(func);
}

  
And it doesn't compile... why ??? If I declare the func as a global function:
  

void func(int a, int b)
{
}

  
and:
  

void test2::Init()
{
	test1		qqq;

	qqq.Init(::func);
}

  
it compiles !! Please, help... thx, ferceg Edited by - ferceg on November 15, 2001 10:08:48 AM

Share this post


Link to post
Share on other sites
this is because the function is inside the class and the pointer to a function in a class isn''t the same as a global function pointer - you could try making the class function static, that should probably work.

A pointer to a non static object function must look diffrent due to member data and such.

a way to solve this is to pass the pointer of test2 instead - like this...

class test1
{
private:
test2 * t2;
public:
void Init(test2 *t2);

void dosomething(){
t2->func(0,0);
}

};

//test2:

class test2
{
public:

void func(int a, int b);
void Init();
};

void test2::Init()
{
test1 qqq;

qqq.Init(this);
qqq.dosomething(); // this calls this->func(0,0);
}

Share this post


Link to post
Share on other sites
non static member function pointers need to be qualified with the class name like:

typedef void (test2::funcptr)(int, int);

All non static member functions need an implicit this parameter, which is why the compiler chokes when you try to pass the member function.

see:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html

Share this post


Link to post
Share on other sites
if you are using classes i would suggest avoiding using function pointers.

this is because functions in classes either need an object to be associated with or they need to be static.

if they are static, then all instances of that class that use the static function will all work with the same data which will probably void the point of using different instances in the first place.

instead I would suggest passing class pointers, as already suggested

Share this post


Link to post
Share on other sites