I was having a problem getting a function to accept an enum as a return-type. In the code below there's an enum:
Status{ DEAD, WOUNDED, HEALTHY }
and a function with Status as a return type:
Status getStatus();
Header Code:
class Discovery
{
public:
void doCombat( int );
void setCombatThreshold( int );
void setHealth( int );
void setStatus( int );
Status getStatus();
private:
enum Status { DEAD, WOUNDED, HEALTHY };
Status charStatus;
int yourHealth;
int combatThreshold;
};
Initially the associated function definition read:
Status Discovery::getStatus()
{
switch ( charStatus )
{
case DEAD:
return DEAD;
break;
case WOUNDED:
return WOUNDED;
break;
case HEALTHY:
return HEALTHY;
break;
};
}
I found this answer: returning enum from function in C++ base class which helped me realize I really needed the first line of the function to read:
Discovery::Status Discovery::getStatus()
But, I was still receiving a 'missing type specifier' error for my header code. I realized that having my 'enum Status' declaration under the private access-specifier might be making the difference, so I moved it to the public access-specifier in my header code. It worked! But I'd like some elucidation on why it wouldn't work under the private access-specifier. What I've managed to find elsewhere is:
Objects of the class cannot access private data members.
My interpretation of what happened being - with the enum-type definition under the private access-specifier, the function (and eventually an object calling that function) couldn't possibly access 'understand' my enum-type, and therefore accept it as a return type.
But - if that's the case, why am I allowed to return variables declared under the private access-specifier with the same problem? Is it because their types are already understood elsewhere, and so the program has no problem accepting them?
Status is defined after it's used. Move status up before the get method.
If you plan to use the enum outside of the class you will want to move the enum into public scope.