[comp.lang.c++] Pointers to member-functions, what's wrong?

ahuttune@niksula.hut.fi (Ari Juhani Huttunen) (10/15/90)

In short, how do I make this work? What's wrong?
The idea is easy to understand, but I think Turbo-C++ doesn't like me... ;-)

#include <iostream.h>
class c
{
public:
	void f1() { cout << "Function 1...\n"; }
	void f2() { cout << "Function 2...\n"; }
	void dispatch( void (*func)() ) { (*this.*func)(); }
};
main()
{
	c x;
	x.dispatch(c::f1);
	x.dispatch(c::f2);
}
--
  ___  ___  ___  ___  ___  ___  ___  ___  ___  
__I I__I I__I I__I I__I I__I I__I I__I I__I I  Thank you 
 Ari Huttunen    (ahuttune@niksula.hut.fi)  I   for not smoking!
____________________________________________I    <Robocop>

steve@taumet.com (Stephen Clamage) (10/16/90)

ahuttune@niksula.hut.fi (Ari Juhani Huttunen) writes:

>In short, how do I make this work? What's wrong?

>#include <iostream.h>
>class c
>{
>public:
>	void f1() { cout << "Function 1...\n"; }
>	void f2() { cout << "Function 2...\n"; }
>	void dispatch( void (*func)() ) { (*this.*func)(); }
>};
>main()
>{
>	c x;
>	x.dispatch(c::f1);
>	x.dispatch(c::f2);
>}

The problem is that a pointer to a member function is a different kind
of thing than a pointer to an ordinary function.  There are two errors
in your example, and it is the errors that Turbo C++ doesn't like;
I'm sure it likes you just fine.  Here is the corrected example:

#include <iostream.h>
class c
{
public:
	void f1() { cout << "Function 1...\n"; }
	void f2() { cout << "Function 2...\n"; }
	void dispatch( void (c::*func)() ) { (this->*f)(); }
			    ^^^^^^^^^^       ^^^^^^^^^^^^
};
main()
{
	c x;
	x.dispatch(c::f1);
	x.dispatch(c::f2);
}
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com