Yes, I've seen this question and this FAQ (wrong link) this FAQ, but I still don't understand what ->*
and .*
mean in C++.
Those pages provide information about the operators (such as overloading), but don't seem to explain well what they are.
What are ->*
and .*
in C++, and when do you need to use them as compared to ->
and .
?
I hope this example will clear things for you
Now, you can't use
x.somePointer()
, orpx->somePointer()
because there is no such member in class X. For that the special member function pointer call syntax is used... just try a few examples yourself ,you'll get used to itSo called "pointers" to members in C++ are more like offsets, internally. You need both such a member "pointer", and an object, to reference the member in the object. But member "pointers" are used with pointer syntax, hence the name.
There are two ways you can have an object at hand: you have a reference to the object, or you have a pointer to the object.
For the reference, use
.*
to combine it with a member pointer, and for the pointer, use->*
to combine it with a member pointer.However, as a rule, don't use member pointers if you can avoid it.
They obey pretty counter-intuitive rules, and they make it possible to circumvent
protected
access without any explicit casting, that is, inadvertently…Cheers & hth.,
When you have a normal pointer (to an object or a basic type), you would use
*
to dereference it:Conceptually, we're doing the same thing with a member function pointer:
I hope that helps explain the concept. We're effectively dereferencing our pointer to the member function. It's a little more complicated than that -- it's not an absolute pointer to a function in memory, but just an offset, which is applied to
foo
orp
above. But conceptually, we're dereferencing it, much like we would dereference a normal object pointer.EDIT: By the way, it gets weird for virtual member functions pointers.
For member variables:
Member functions are almost the same.
You cannot dereference pointer to members as normal pointers — because member functions require
this
pointer, and you have to pass it somehow. So, you need to use these two operators, with object on one side, and pointer on another, e.g.(object.*ptr)()
.Consider using
function
andbind
(std::
orboost::
, depending on whether you write C++03 or 0x) instead of those, though.In a nutshell: You use
->
and.
if you know what member you want to access. And you use->*
and.*
if you don't know what member you want to access.Example with a simple intrusive list