Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ allow access to an enum through a pointer?

Tags:

c++

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
}
like image 547
Gandalf458 Avatar asked Nov 05 '13 17:11

Gandalf458


People also ask

Should an enum be public or private?

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.

Is enum always public?

Difference between Enums and Classes The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Which is better #define or enum in C?

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 .

Should enum be in header?

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 .


2 Answers

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:

  1. 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.

  2. 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.

like image 74
rici Avatar answered Oct 06 '22 01:10

rici


From C++ ISO/IEC 2011

An enumerator declared in class scope can be referred to using the class member access operators (::, . (dot) and -> (arrow)),

like image 29
Jimbo Avatar answered Oct 06 '22 00:10

Jimbo