function parameters

Started by
3 comments, last by ferceg 22 years, 5 months ago
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
Advertisement
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);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~I'm looking for work
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
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
===========================There are 10 types of people in the world. Those that understand binary and those that don't.( My views in no way reflect the views of my employer. )
Ok, I understand what the problem is...
Thx for the answers !

ferceg

This topic is closed to new replies.

Advertisement