(This is a question after reading this answer)
I tried this code:
#include <iostream>
class A {
public:
int a;
A(int val) : a{val}{}
int f(int);
int (A::*p)(int);
};
int A::f(int in) {
return in + a;
}
int main() {
A a1(1000);
A a2(2000);
// Without these two lines, segmentation fault.
a1.p = &A::f; // no instance information.
a2.p = &A::f; // no instance information.
std::cout << a1.p << " " << a2.p << '\n';
std::cout << std::boolalpha << (a1.p == a2.p) << '\n';
std::cout << (a1.*(a1.p))(5) << '\n';
std::cout << (a1.*(a2.p))(5) << '\n';
std::cout << (a2.*(a1.p))(5) << '\n';
std::cout << (a2.*(a2.p))(5) << std::endl;
}
Results:
1 1
true
1005
1005 // the same result as above.
2005
2005 // the same result as above.
It seems that
a1.p
anda2.p
are the same. Is the member function's address not assigned until it is dereferenced and called by attaching the instance's name?If so, what's the point of assigning
&A::f
, if it has no information about the instance?