[comp.lang.c++] Does ptr to func always work?

daniel@saturn.ucsc.edu (Daniel Edelson) (02/15/89)

Can somebody please enlighten me as to why this does 
not work. It declares a member that points to a
member function. The constructor initializes
the pointer based on an argument. When calling 
through the pointer to function the argument gets lost.

This can be fixed with pointers to member 
but I'd like to understand why it doesn't work
as simple pointers to functions. 

We've tried this under cfront 1.2.1 and under oregon C++.

#include <stream.h>

typedef void  (*ptr_f)(int);	// simple pointer to func type

class FUNC {
public:
    ptr_f  pF;
    void F1(int i) { cout << "F1:  " << i << "\n"; }
    void F2(int i) { cout << "F2:  " << i << "\n"; }
    FUNC(int i) {
		if (i==0)  pF= (ptr_f) &(FUNC::F1);	// point at F1
			else   pF= (ptr_f) &(FUNC::F2);	// point at F2
    }
};

main()
{
    FUNC Q(1);	// Select F2

    Q.F1(10000);	// invoke F1 directly
    Q.F2(10000);	// invoke F2 directly
    (Q.pF)(10000);	// invoke F2 indirectly, 10000 gets lost
}

A solution using pointers to member is:

#include <stream.h>

class FUNC ;		// forward decl

typedef void  (FUNC::*ptr_mf)(int);	// pointer to member type

class FUNC {
public:
    ptr_mf  pF;
    void F1(int i) { cout << "F1:  " << i << "\n"; }
    void F2(int i) { cout << "F2:  " << i << "\n"; }
    FUNC(int i) {
			if(i==0) pF= &(FUNC::F1);
			else     pF= &(FUNC::F2);
		}
};

main()
{
    FUNC Q(1);

    Q.F1(10000);
    Q.F2(10000);
    (Q.*(Q.pF))(10000);		//Yuck!
}

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Daniel Edelson
daniel@saturn.ucsc.edu