Path: utzoo!attcan!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: Address of member function Message-ID: <491@taumet.com> Date: 28 Oct 90 16:52:59 GMT References: <1399@carol.fwi.uva.nl> Organization: Taumetric Corporation, San Diego Lines: 47 delft@fwi.uva.nl (Andre van Delft) writes: >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 [nonstatic] MEMBER FUNCTION, i.e. a function local to an instance of a class The problem comes with virtual functions. Suppose that you could take the address of a virtual member function. You would still have to call it in conjuction with some object (so "this" could refer to something). Suppose we had something like class C { ... public: virtual f(); g();... }; class D : public C { ... public: virtual f(); ... }; D d; void (*fp)() = c.f; // presently illegal C* cp = &d; 1. cp->f(); // virtual call, in this case calls dp->D::f() 2. cp->fp(); // invented sytax -- what do we do here? 3. fp(); // ok if fp had the address of an ordinary function As you can see from 2 & 3, we still must distinguish between a pointer to a non-static member function and a pointer to an ordinary function. The compiler would otherwise not be able to tell whether it should add a "this" pointer and thus whether the call was even legal. In 1, the C* variable really holds a D*, and so D::f() gets called -- this is the definition of a virtual function. What do we do with 2? We only have the address of C::f(), so we can't call D::f(), and we have lost polymorphism. That is, the behavior of a class object depends on whether a certain kind of pointer is used to access it. Ugh. Also note that fp could also be made to point to C::g(), since it has the same type as C::f(), but is not virtual. So we have a new kind of pointer type, a pointer-to-member-function, which may point to a virtual or non-virtual member function. Such an object is not the same kind of object as other pointers because it must deal with different kinds of issues. -- Steve Clamage, TauMetric Corp, steve@taumet.com