How should this call to ofAddListener look?

Having a bit of difficulty figuring out how to use ofAddListener in this situation:

  
void testApp::mousePressed(int x, int y, int button){  
	ParamChange *newParamChange = new ParamChange();  
	// Problem here   
	ofAddListener(this->newSamplePosEvent, *newParamChange, *newParamChange::newPos);  
	paramChanges.push_back(newParamChange);  
}  

testApp.cpp will generate events called newSamplePosEvent. What i’m trying to do here is instantiate a ParamChange object when the mouse is clicked, and tell this new object to listen for newSamplePosEvent events from testApp, and to respond by firing its own newPos method. But i’m a bit lost as to the syntax for correctly indicating the listener method (the above code fails because the ofAddListener isn’t correct). Can anyone lend a hand?

Hi bitbutter
the last two parameters of ofAddListener are pointers.
“newParamChange” is already a pointer so you can just pass that in (without the * symbol)
For the second parameter you need to create a pointer to a method.
To create a pointer to an object you add the & symbol before it (and not the * )
like this:

  
  
SomeObject myObject;  
SomeObject * objectPointer = &myObject;  
  

so your call to ofAddListener should be something like this

  
  
ofAddListener(this->newSamplePosEvent, newParamChange, &newParamChange::newPos);  
  

just make sure you eventually delete all these objects you are creating at every mouse press, so you don’t get a memory leak :slight_smile:

best

Rui

Thanks pelintra, that’s useful.

I’m still not understanding something it seems, here’s how i changed the function:

  
void testApp::mousePressed(int x, int y, int button){  
	ParamChange *newParamChange = new ParamChange();  
	newParamChange->setPos(pos);  
	ofAddListener(this->newSamplePosEvent, newParamChange, &newParamChange::newPos);  
	paramChanges.push_back(newParamChange);  
}  

The compiler complains about the last argument to ofAddListener:
“‘newParamChange’ is not a class or namespace
‘newPos’ was not declared in this scope”

hi

the sintax for ofAddListener is:

  
ofAddListener(event, ptr_to_instantce, &class::method);  

what you’re using is:

  
ofAddListener(event, ptr_to_instantce, &instance::method);  

note the final parameter instance/class difference. so

  
ofAddListener(this->newSamplePosEvent, newParamChange, &newParamChange::newPos);  

should be:

  
ofAddListener(this->newSamplePosEvent, newParamChange, &ParamChange::newPos);  

Thanks arturo, that makes sense also. In fact i’d already tried that, but was discouraged by a compiler error which i didn’t understand the cause of. Here’s how the error looks:

(I really appreciate your collective patience by the way!)

the correct syntax for the newPos method is something like:

  
void newPos(int & pos);  

Ah i see, i think; OF expects the method added by addlistener to receive a reference as its argument (?). That gets me further, thanks!