C++ define class member struct and return it in a member function

yolo picture yolo · Apr 2, 2011 · Viewed 36.3k times · Source

My goal is a class like:

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

userInfo UserInformation::getInfo(int userId)
{
    infoStruct.repu = 1000; 
    return infoStruct;
}

but the compiler gives error that in defintion of the public function getInfo(int) the return type userInfo is not a type name.

Answer

pic11 picture pic11 · Apr 2, 2011

It makes sense to make the nested structure type public, since the user code should be able to use it. Also, place the declaration of the structure before the point of its first use. Outside the class scope use scope resolution :: to refer to nested types.

class UserInformation
{
public:
    struct UserInfo
    {
        int repu, quesCount, ansCount;
    };


public:
    UserInfo getInfo(int userId);

private:
    UserInfo infoStruct;
    int date;
};

UserInformation::UserInfo UserInformation::getInfo(int userId)
{
    infoStruct.repu = 1000;
    return infoStruct;
}