Reputation: 2269
I am working on some code where there is a simple enum in a class. A different piece of code has a pointer to that class and is accessing a value of the enum through the arrow pointer.
How on earth is the class able to access MY_VALUE1 this way? I though it would only allow access via MyClass::MY_VALUE1 or MyClass::MyEnum::MY_VALUE1.
class MyClass {
public:
enum MyEnum{
MY_VALUE0 = 0,
MY_VALUE1 = 1
};
//getters, setters as appropriate
};
//Other class
MyClass* myClass = new MyClass();
//Compiles without C++11
if(getRandomEnum() == myClass->MY_VALUE1)
{
//Do Stuff
}
Upvotes: 5
Views: 1456
Reputation: 241691
The ->
operator is (mostly) an abbreviation for dereference
(*) and selection
(.). In other words, a->b
is the same as (*(a)).b
. (§5.2.5/2; See notes below).
The . syntax is class member access, as defined by §5.2.5 [expr.ref]; the identifier on the right-hand side of the . can be a static or non-static data member, function, or member enumerator (paragraph 4 of the cited section). It cannot be a nested type. In this sense, member enumerators are syntactically similar to static const
data members.
Notes:
As §13.5.6 clarifies, a->b
is is subject to operator overloading. If a
is not a pointer type, then ->
may be overloaded, in which case the expression is interpreted as (a.operator->())->b
. Eventually, the sequence of overloaded ->
calls must result in a pointer type, at which point the interpretation of §5.2.5/2 is applied.
An important difference between Class::member
and value.member
is that in the second case, value
will be evaluated even if that is unnecessary to resolve the value of member
.
Upvotes: 6
Reputation: 153909
The enum values are treated much as if they were static members
of the class, and can be accessed in two ways: via the class
name followed by the scope resolution operator
(MyClass::MY_VALUE0
), or like any other member
(instance.MY_VALUE0
or pointer->MY_VALUE0
).
Note that in the latter case, the operand on the left is still
evaluated, even though the results of the evaluation is not
used. In other words, if I write f()->MY_VALUE0
(where f()
returns a MyClass*
), the function will be called, despite the
fact that its return value is not used.
Upvotes: 2
Reputation: 4515
From C++ ISO/IEC 2011
An enumerator declared in class scope can be referred to using the class member access operators (::, . (dot) and -> (arrow)),
Upvotes: 3