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
}
An enum is a type, not a data member. You should make it public if users of the class need to know about it; otherwise, make it private. A typical situation where users need to know about it is when it's used as the type of an argument to a public member function.
Difference between Enums and Classes The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).
In C, enum is preferable only when we are working with natural group of constants. In all other cases it is #define and only #define .
Your code (e.g. your enum) SHOULD be placed in the . h file if you need to expose it to the code you're including the . h file. However if the enum is only specific to the code in your header's .
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
.
From C++ ISO/IEC 2011
An enumerator declared in class scope can be referred to using the class member access operators (::, . (dot) and -> (arrow)),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With