I came across this strange code snippet which compiles fine:
class Car { public: int speed; }; int main() { int Car::*pSpeed = &Car::speed; return 0; }
Why does C++ have this pointer to a non-static data member of a class? What is the use of this strange pointer in real code?
It’s a ‘pointer to member’ – the following code illustrates its use:
As to why you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I’ve never had to use them in my own code.
Edit: I can’t think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try – an Apply function that would do some pre &post processing before applying a user-selected member function to an object:
The parentheses around
c->*funcare necessary because the->*operator has lower precedence than the function call operator.