Search code examples
c++classfunctionstructclass-members

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


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.


Solution

  • You need to change the order of the members of UserInformation and put struct UserInfo above the declaration of getInfo. The compiler complains that it can't work out the signature for getInfo because it hasn't seen the definition of its return type yet.

    Also, if you are returning a struct from the function the type of the struct must be visible to the callers. So you need to make the struct public as well.