In c++ is there any difference between these 3 blocks of code:
MyClass->m_Integer // 1
MyClass::m_Integer // 2
MyClass.m_Integer // 3
In c++ is there any difference between these 3 blocks of code:
MyClass->m_Integer // 1
MyClass::m_Integer // 2
MyClass.m_Integer // 3
On
-> means MyClass is a pointer to the class and said pointer needs to be dereferenced in order to get to member m_Integer
:: is the scope or namespace operator. It means that m_Integer is either static or needs you need to identify specifically which scope or namespace m_Integer is within.
. means that m_Integer is being access directly (not through a pointer) from MyClass. It pretty much how you would access memebers from within Java as well and should be the one you are most familiar with.
On
Along with the other answers you've gotten, it's worth noting that operator-> can be overloaded. You've already gotten some reasonable explanations of how the built-in version work, but an overloaded operator-> is somewhat unusual, so perhaps it's worth adding a bit about how it works.
The standard describes how operator-> is unusual fairly succinctly (ยง13.5.6):
An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).
This has a couple of implications:
-> looks like a binary operator, from a viewpoint of overloading, it's essentially a unary operator -- your overload will be a member function that takes no argument.operator->, or else a pointer to some object (of class or struct type).Since you can return an object that itself overloads operator->, an expression of the form x->m can hide an arbitrary amount of complexity (an arbitrary number of functions being called). What you write as x->m could really expand out to x->y->z->a->b->...m.
The
->and.operators are way to access members of an instance of a class, and::allows you to access static members of a class.The difference between
->and.is that the arrow is for access through pointers to instances, where the dot is for access to values (non-pointers).For example, let's say you have a class
MyClassdefined as:You would use those operators in the following situations:
In Java, this would look like: