Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "->" operator mean in C++?

Could someone explain to me what the "->" means in C++?

Examples if you can, they help me understand better. Thanks.

like image 332
Bumrang Avatar asked Sep 06 '25 03:09

Bumrang


2 Answers

It's a shortcut for dereference followed by property access (or method invocation).

In code, here are some examples of this equivalence:

Foo *foo;

// field access
foo->bar = 10;
(*foo).bar = 10;

// method invocation
foo->baz();
(*foo).baz();

This is especially convenient when you have a long sequence of these. For example, if you have a singly linked list data structure in which each element has a pointer to the next, the following are equivalent ways of finding the fifth element (but one looks much nicer):

linked_list *head, *fifth;
fifth = head->next->next->next->next;
fifth = (*(*(*(*head).next).next).next).next;
like image 112
Jeremy Roman Avatar answered Sep 07 '25 21:09

Jeremy Roman


It's often called the "member access" operator. Basically, a->b is a nicer way to write (*a).b. You can think of a->b as "access the b member/function in the object a points to". You can read it aloud (or think it to yourself) as "a member access b".

In a random sample of structured C++ code I just checked (from several different projects written by different people), 10% of lines of code (not counting headers) contained at least one member access operator.

like image 21
David Schwartz Avatar answered Sep 07 '25 22:09

David Schwartz