C++ – When do I use a dot, arrow, or double colon to refer to members of a class in C++

cc++-faq

Coming from other C-derived languages (like Java or C#) to C++, it is at first very confusing that C++ has three ways to refer to members of a class: a::b, a.b, and a->b. When do I use which one of these operators?


_(Note: This is meant to be an entry to [Stack Overflow's C++ FAQ](https://stackoverflow.com/questions/tagged/c++-faq). If you want to critique the idea of providing an FAQ in this form, then [the posting on meta that started all this](https://meta.stackexchange.com/questions/68647/setting-up-a-faq-for-the-c-tag) would be the place to do that. Answers to that question are monitored in the [C++ chatroom](https://chat.stackoverflow.com/rooms/10/c-lounge), where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)_

Best Answer

The three distinct operators C++ uses to access the members of a class or class object, namely the double colon ::, the dot ., and the arrow ->, are used for three different scenarios that are always well-defined. Knowing this allows you to immediately know quite a lot about a and b just by looking at a::b, a.b, or a->b, respectively, in any code you look at.

  1. a::b is only used if b is a member of the class (or namespace) a. That is, in this case a will always be the name of a class (or namespace).

  2. a.b is only used if b is a member of the object (or reference to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class.

  3. a->b is, originally, a shorthand notation for (*a).b. However, -> is the only of the member access operators that can be overloaded, so if a is an object of a class that overloads operator-> (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented. To conclude: With a->b, if a is a pointer, b will be a member of the object the pointer a refers to. If, however, a is an object of a class that overloads this operator, then the overloaded operator function operator->() gets invoked.


The small print:

  • In C++, types declared as class, struct, or union are considered "of class type". So the above refers to all three of them.
  • References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the #3 as well. However, I thought this would be more confusing than helpful, since references to pointers (T*&) are rarely ever used.
  • The dot and arrow operators can be used to refer to static class members from an object, even though they are not members of the object. (Thanks to Oli for pointing this out!)