c++classscope-resolution-operator

Scope resolution operator for returning a nested class type


I know that the scope resolution operator :: is used to identify and disambiguate identifiers used in different scopes.

In the example provided here C++ define class member struct and return it in a member function

class UserInformation
{
public:
    userInfo getInfo(int userId);
private:
    struct userInfo
    {
        int repu, quesCount, ansCount;
    };
    userInfo infoStruct;
    int date;
};

You can create a member function that returns a type of the nested class userInfo.

UserInformation::UserInfo UserInformation::getInfo(int userId)   <-----
{
    Userinfo x;            <-----
    infoStruct.repu = 1000;
    return infoStruct;
}
  1. Why does the scope have to be stated twice in the function definition? UserInformation::UserInfo UserInformation::getInfo(int userId) It's an error if it's only stated once, but from my understanding, I thought that stating it once at the beginning, before the return value would put us in the correct scope already?
  2. In the function above, I added Userinfo x; to show that the nested class type can be declared and used without the scope resolution operator. Why is that allowed?

Solution

    1. The class scope is needed for the function return type because name lookup won't yet know of it.

    You can get around that requirement if you wish with C++11 trailing function return type.

    auto UserInformation::getInfo(int userId) -> UserInfo
    { ... }
    
    1. The class scope is not needed inside the member function body because there the class scope is then obviously known.