[prev in list] [next in list] [prev in thread] [next in thread] 

List:       gcc
Subject:    Re: Ignorant question about printf warnings for pointer-to-member functions
From:       Matthias Benkmann <matthias () winterdrache ! de>
Date:       2002-11-30 19:21:29
[Download RAW message or body]

The following example should make clear why even if it was desirable to
have member function "pointers" implemented as "real pointers" (i.e.
memory addresses), such an is implementation is simply impossible/does not
make sense:

----------------------------
#include <iostream>

class A {
public: virtual void foo()=0;
};

class B: public A {
public: virtual void foo() {std::cout<<"foo"<<std::endl;};
};

class C: public A {
public: virtual void foo() {std::cout<<"bar"<<std::endl;};
};

int main()
{
  void (A::*fooptr)();
  fooptr=&A::foo;  /* what "address" should fooptr point to? */
  C c;
  B b;
  (c.*fooptr)(); /* access C::foo() via fooptr */
  (b.*fooptr)(); /* access B::foo() via fooptr */
};
---------------------------

As you can see, a member function "pointer" can point to a pure virtual
function, i.e. a function that does not really exist. It has no code. What
memory address should the pointer hold?
But it gets worse. As the example shows, the same pointer can refer to
different functions depending on the context in which it is used. In the
context of a C object, fooptr "points to" C::foo()  (which is a real
function with a memory address). In the context of a B object, fooptr
"points to" B::foo()  (which is also a real function with a real memory
address, different from that of C::foo())

MSB

p.s.: It would be very nice if someone could give a (pointer to a) brief
explanation of how GCC implements member pointers. Is it the same
structure for data members and methods, virtual and non-virtual? Or does
GCC use optimized techniques for the different types of member pointers.

-- 
Bad comments reveal the bad programmer.

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic