Possible Duplicates:
What is the difference between the dot (.) operator and -> in C++?
What is the arrow operator (->) synonym for in C++?
The header says it all.
What does -> mean in C++?
Possible Duplicates:
What is the difference between the dot (.) operator and -> in C++?
What is the arrow operator (->) synonym for in C++?
The header says it all.
What does -> mean in C++?
It's to access a member function or member variable of an object through a pointer, as opposed to a regular variable or reference.
For example: with a regular variable or reference, you use the .
operator to access member functions or member variables.
std::string s = "abc";
std::cout << s.length() << std::endl;
But if you're working with a pointer, you need to use the ->
operator:
std::string* s = new std::string("abc");
std::cout << s->length() << std::endl;
It can also be overloaded to perform a specific function for a certain object type. Smart pointers like shared_ptr
and unique_ptr
, as well as STL container iterators, overload this operator to mimic native pointer semantics.
For example:
std::map<int, int>::iterator it = mymap.begin(), end = mymap.end();
for (; it != end; ++it)
std::cout << it->first << std::endl;
a->b
means (*a).b
.
If a
is a pointer, a->b
is the member b
of which a
points to.
a
can also be a pointer like object (like a vector<bool>
's stub) override the operators.
(if you don't know what a pointer is, you have another question)
a.operator->()
to be different from &*a
is evil.
Introducer for the return type of a local lambda expression:
std::vector<MyType> seq;
// fill with instances...
std::sort(seq.begin(), seq.end(),
[] (const MyType& a, const MyType& b) -> bool {
return a.Content < b.Content;
});
introducing a trailing return type of a function in combination of the re-invented auto
:
struct MyType {
// declares a member function returning std::string
auto foo(int) -> std::string;
};
x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators
a -> b
is member b of object pointed to by a
The ->
operator, which is applied exclusively to pointers, is needed to obtain the specified field or method of the object referenced by the pointer. (this applies also to structs
just for their fields)
If you have a variable ptr
declared as a pointer you can think of it as (*ptr).field
.
A side node that I add just to make pedantic people happy: AS ALMOST EVERY OPERATOR you can define a different semantic of the operator by overloading it for your classes.