What is the difference between the dot (.) operator and -> in C++?
The . operator is for direct member access.
object.Field
The arrow dereferences a pointer so you can access the object/memory it is pointing to
pClass->Field
The arrow operator is like dot, except it dereferences a pointer first. foo.bar()
calls method bar()
on object foo
, foo->bar
calls method bar
on the object pointed to by pointer foo
.
-> use when you have pointer
. use when you have structure (class)
when you want point attribute that belong to structure use . structure.attribute
when want point to attribute that have refference to memory by pointer use -> :
pointer->method;
or same as:
(*pointer).method
The target. dot works on objects; arrow works on pointers to objects.
std::string str("foo");
std::string * pstr = new std::string("foo");
str.size ();
pstr->size ();
Dot operator can't be overloaded, arrow operator can be overloaded. Arrow operator is generally meant to be applied to pointers (or objects that behave like pointers, like smart pointers). Dot operator can't be applied to pointers.
EDIT When applied to pointer arrow operator is equivalent to applying dot operator to pointee (ptr->field is equivalent to (*ptr).field)
foo->bar()
is the same as (*foo).bar()
http://stackoverflow.com/questions/221346/what-is-the-arrow-operator-synonym-for-in-c
pSomething->someMember
is equavivalent to
(*pSomething).someMember
It's simple, whenever you see
x->y
know it is the same as
(*x).y
The . (dot) operator is usually used to get a field / call a method from an instance of class (or a static field / method of a class).
p.myField, p.myMethod() - p instance of a class
The -> (arrow) operator is used to get a field / call a method from the content pointed by the class.
p->myField, p->myMethod() - p points to a class
Note that the -> operator cannot be used for certain things, for instance, accessing operator[].
#include <vector>
int main()
{
std::vector<int> iVec;
iVec.push_back(42);
std::vector<int>* iVecPtr = &iVec;
//int i = iVecPtr->[0]; // Does not compile
int i = (*iVecPtr)[0]; // Compiles.
}
The -> is simply syntactic sugar for a pointer dereference,
As others have said:
pointer->method();
is a simple method of saying:
(*pointer).method();
For more pointer fun, check out Binky, and his magic wand of dereferencing:
For a pointer, we could just use
*pointervariable.foo
But the . operator has greater precedence than the * operator, so . is evaluated first. So we need to force this with parenthesis:
(*pointervariable).foo
But typing the ()'s all the time is hard, so they developed ->
as a shortcut to say the same thing. If you are accessing a property of an object or object reference, use .
If you are accessing a property of an object through a pointer, use ->
;D
(Dot) The target . dot work on object
(Arrow) Arrow work on pointer to the object
(Example of Dot)
(*pointer).method
(Example of Arrow)
pointer->method