TITLE: Calling static class members via pointers


PROBLEM: doug@foxtrot.ccmrc.ucsb.edu (Douglas Scott)

Is it possible to call a static member function via a pointer without having
an instance of the class present at the time? 

The following code is clearly wrong:

class FunClass {
public:
	static int foo();
};

int FunClass::foo() { return 1; }

typedef /* static? */ int (FunClass::*ClassFun)();


main() {
	ClassFun fun = FunClass::foo;	// incompatible -- why?

	printf("%d\n", (FunClass::*fun)());	// parse error here
}



RESPONSE: adk@Warren.MENTORG.COM (Ajay Kamdar)


Yes, it is possible to call a static member function via a pointer
without having an instance of the class present at the time.

This typedef is wrong. A pointer to a static member function is
declared as if the function was not a member function.
See example below.

This is the proper way to do what you want:

#include <iostream.h>

class FunClass {
public:
    static int foo();
};

int FunClass::foo() {return 1;}
    // static member function

int bar() {return 0;}
    // not a member function. Yet has the same signature as FunClass::foo

typedef int (*PF)();

main()
{
    PF fun = FunClass::foo;
    cout << fun() << endl;    // will print 1
    fun = bar;
    cout << fun() << endl;    // will print 0
}
