YAKOVM
YAKOVM

Reputation: 10153

Return enum from member function

I want to mplement function that returns enum:

class myClass{
    private:
    res _res;
    public:
    enum res{ok,fail};
    res getRes()
    bool checkRes(res r);
    //other function that change _res value
    }

This implementation generates compilation error:

res myClass::getRes(){return _res;}

But the following is OK:

myClass::res myClass::getRes(){return _res;}

Why enum return type should be specified by scope ,while as an argument type scope for enum is not necessary - the following works OK:

 bool myClass::checkRes(res r){
     if (_res == r){retun true;}
     else {return false;} }

Upvotes: 3

Views: 4876

Answers (1)

Xeo
Xeo

Reputation: 131799

Because the return type is not in the lexical scope of the class. If you have a C++11 aware compiler that supports it, use the trailing return type (also called late-specified return type):

auto myClass::getRest() -> res{ return _res; }

The part after -> (infact, even the paramter list) already belongs to the lexical scope of the class, as such no qualifications are necessary.

Upvotes: 7

Related Questions