Jump to content
  • Advertisement
Sign in to follow this  
ronnybrendel

callbacks and classes

This topic is 4431 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i want to add functions to an array to call them later. i know its not possible over different classes, except with static declarations i tested a little and got stuck ... it should be used for example as callbacks for actions in an inputsystem( for mouse and keyboard) compiler says he cant cast int testfunc"( int, char*)" into "somefunc (__cdecl *)" ... any suggestions ?
typedef int (somefunc)( int a, char *b);

class A {

public:
	
	somefunc *funcs[10];
	int counter;

	A() {

		memset( funcs, 0, sizeof( somefunc* ) * 10 );
		counter= 0;
	}


	void addAction( somefunc *func) {

		funcs[counter]= func;
		++counter;
	}


	void go() {

		for( int i= 0; i < counter; ++i ) {

			if( NULL != funcs ) {

				funcs( i, 0 );
			}
		}
	}
};


class B : public A {

public:

	int testfunc( int a, char *b ) {

		printf( "huhu %i\n", a );
		
		return 0;
	}

	B() : A() {

		addAction( testfunc );
		
	}
	

};

int main( int argc, char **args ) {


	B test;

      B.go();

	return 0;
}


Share this post


Link to post
Share on other sites
Advertisement
testfunc is a member function, and these have special rules in c++. Specifically, the compiler silently makes it so that member functions recieve a hidden "this" pointer.

The syntax for pointer to member functions isnt pretty.

Here is a link that talks about it...

Note that if you had testfunc as a free floating function, or as a tatic function, you're code would probably work.

Good Luck!

Share this post


Link to post
Share on other sites
You could try using the boost::function library with which you can mix function pointers with member function pointers :)´

If you just want the learning experience you could always write a functor of your own, it's not too much code for simple functors with low parameter counts, but it requires some template fiddling :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!