Arrow Operator in C++
C++
In C++ .
is the standard member access operator. It has higher precedence than the *
dereference operator.
Accessing the member of an object through a pointer requires dereferencing to happen first, so the dereferencing operation must be wrapped in parentheses.
Example 1: Access Member Variable
int main()
{
struct Resource {
int id;
const char * name;
};
struct Resource mainPerson{1, "Cornelius"};
Resource *p = &mainPerson;
// Dereference first, then access member variable:
std::cout << "ID:\t" << (*p).id << std::endl;
std::cout << "ID:\t" << (*p).name << std::endl;
// Equivalent:
std::cout << "ID:\t" << p->id << std::endl;
std::cout << "Name:\t" << p->name << std::endl;
return 0;
}
Example 2: Iterate over a Map
When you use iterators to loop through a container, you need to dereference the iterator to access each object. The arrow operator can provide a convenient shortcut for this:
int main()
{
std::map<std::string, double> myMap{{"David", 99.9}, {"Elaine", 99.99}, {"Bill", 45}};
std::map<std::string, double>::iterator myMapIt;
for (myMapIt = myMap.begin(); myMapIt != myMap.end(); myMapIt++) {
// Accessing the member requires dereferencing to happen first,
// hence the placement of parentheses:
std::cout << (*myMapIt).first << ": " << (*myMapIt).second << std::endl;
// The arrow operator is shorthand for this, providing member access by an
// indirect selector. This is equivalent to the line above:
std::cout << myMapIt->first << ": " << myMapIt->second << std::endl;
}
return 0;
}
comments powered by Disqus