Apr 2, 2011 at 7:06pm UTC
Dear All,
I have encountered an unexpected result when overloading the pointer-to-member function. In the following code:
#include <iostream>
using namespace std;
class X {
public:
void f() { cerr << "f() called!" << endl; }
void operator() () { cerr << "operator() called!" << endl; }
X operator->* (void (X::*pmf)()) { cerr << "operator->* called!" << endl; return *this; }
} x;
int main (int argc, char **argv) {
void (X::*p)() = &X::f; ((&x)->*p)();
return 0;
}
I would have expected the output:
operator->* called!
operator() called!
But instead I get the output
f() called!
which indicates to me that the overloading was not succesfull.
Could someone kindly point out what mistake I am making here?
Many thanks,
Shen
Apr 2, 2011 at 7:13pm UTC
You would have gotten "operator() called!" is your code was "x()" and "operator->* called!" if it was "x->*p".
Here the left argument of ->* is X* and not X.
Apr 2, 2011 at 7:27pm UTC
Thank you very much for your quick and insightful response.
Is there a possibility to overload ->* in such a way that
((&x)->*p)();
calls operator->*?
Many thanks.
Shen
Apr 3, 2011 at 8:54am UTC
It is possible to define ->* outside a class (so that the left argument is X*) but C++ doesn't allow to overload operators when both arguments are pointers, so no (unless you overload & too).
Apr 3, 2011 at 3:28pm UTC
Thanks a lot! That answers my question.