Xref: utzoo comp.lang.c++:10121 comp.std.c++:380 Path: utzoo!attcan!uunet!mcsun!hp4nl!fwi.uva.nl!delft From: delft@fwi.uva.nl (Andre van Delft) Newsgroups: comp.lang.c++,comp.std.c++ Subject: Address of member function Message-ID: <1399@carol.fwi.uva.nl> Date: 27 Oct 90 20:16:28 GMT Sender: news@fwi.uva.nl Reply-To: delft@fwi.uva.nl (Andre van Delft) Followup-To: comp.lang.c++ Organization: Faculteit Wiskunde & Informatica, Universiteit van Amsterdam Lines: 85 A few days ago I had a question on comp.lang.c++ about taking the address of a member function: >>For a call-back mechanism, I want to store the address of a non-static >>class member function. Turbo-C++ does not allow this ("member function >>pointers are not true pointer types, and do not refer to any particular >>instance of a class"). >> >>What does ANSI-C++ say about this? Are C++ implementations free to >>decide whether addresses of member functions are normal addresses? >>If so, what do other C++ implementations decide? ("ANSI-C++" should have been "AT&T C++, 2.0", of course.) Thanks those who responded. However, my question was not well understood by some, e.g., >It doesn't make sense to call a class member function without an instance of >that class. It *should* be illegal. I meant the following: why is it allowed to take the address of: a GLOBAL VARIABLE a GLOBAL FUNCTION a MEMBER VARIABLE, i.e. a variable local to an instance of a class but why is it NOT allowed to take the address of a MEMBER FUNCTION, i.e. a function local to an instance of a class Example: int i; int f(int k) {printf("%d\n",i+k);} class c { public: int j; int g(int k) {printf("%d\n",j+k);} } main() { int*ip,*jp; int(*fp)(int); int(*gp)(int); c anObject; ip = & i; // OK jp = &anObject.j; // OK fp = & f; // OK gp = &anObject.g; // NOT OK *ip = 1; *jp = 2; fp(3); // prints 4 gp(4); // would print 6, if not NOT OK ... } I want the address of g() as belonging to anObject, and this address should have the same size of any address. Current C++ implementations do not allow this: it is reasonable that any instance of a class has its own space for its instance variables, but it would be inefficient when it also had the complete code for its member functions for itself. Instead, most C++ versions implement a member function as a global function with an extra parameter that points to the object to which the message is directed. Something like: int cg(c*,int) for c::g with actual use cg(&anObject,5) for anObject.g(5)). However, it would not be too inefficient to put part of the member function code in the space of each instance: in 'anObject', this "present" 'g' function would just call 'cg' with 'this' as extra parameter: 'cg(this,5)'. With a new "access modifier" programmers could force such present functions, so that taking their address would be legal, without overhead for nonpresent functions: class c { public: int j; present int g(int k) {printf("%d\n",j+k);} } Andre van Delft DELFT@fwi.uva.nl