-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 01/07/2011 02:06 PM, Paul wrote:
[...]
I can understand the concept you express but
a) how do you get the address of a member function?
&ClassName::functionName
Concretely:
struct C { void f(); };
void (C::*pf)() = &C::f;
b) what happens if this member function is virtual?
It works correctly. That's why pointer to member functions are
often larger than any other pointer types (but there are other
ways of solving the problem).
What would your pointer point to ?
That's the compiler writers problem, not mine
.
It certainly is a problem for the compiler, and perhaps the program
too.
Especially if you didn't initialised the empty pointer.
Let me put it another way, where would you get the address for the
virtual function?
You cannot do this with virtual functions and you are wrong
to suggest it works correctly.
It does work, and I've done it. More than once.
It simply can't be done as the concept of virtual functions only lives
in the world of objects.
Please show some basic code. I guarantee you cannot.
#include <iostream>
class C1 {
public:
virtual void f() {
std::cout << "C1::f" << std::endl;
}
};
class C2 : public C1 {
public:
virtual void f() {
std::cout << "C2::f" << std::endl;
}
};
int main () {
void (C1::*p)() = &C1::f; //create a pointer to a member function
C1 a; //create a object of type C1
C1 * b; //create a object of type pointer to C1
The challenge put forward was to invoke a virtual function without
creating an object. Here you have created an object.
I applaud your abilities nonetheless, assuming the code is correct.
b = new C2(); //allocate a object of type C2
(a.*p)(); //call the member function pointed to
//by p, with &a as this
(b->*p)(); //call the member function pointed to
//by p (virtually), with b as this
return 0;
}
This code prints the following.
C1::f
C2::f
The very nature of virtual functions require objects and perhaps you
have demostrated this.
This was what i was referring when I initially stated 'it won't work
with virtual functions':
"You can take the address of a member function (and assign it to a
function pointer of the proper type), and it will *not* be tied to any
specific object."