Pgram
Pgram

Reputation: 81

return the value in a struct from method of a class

#include <iostream>
using namespace std;

struct AccountInfo
{
    int Acnumber;
    char ID;
};

class Account
{
    public:
        AccountInfo Operation(void)
        {
            AccountInfo s;
            s.ID = 'M';
            return s;

        }
};

int main()
{
    Account a;
    AccountInfo s = a.Operation();
    cout << s.ID << endl;

    return 0;
}     

I am trying to return the values given to a structure inside the method of a class. The code compiles with errors. I tried using an object, it compiles successfully, but doesn't output anything.

What is the problem with my code?

Upvotes: 0

Views: 58

Answers (2)

David G
David G

Reputation: 96790

struct Operation(void)

What type does this function return? It can't be struct because that's not a type, it's a keyword denoting a structure definition. Judging from the return value and how you are using it, I'm assuming you're trying to return an AccountInfo object:

AccountInfo Operation()
{
    AccountInfo s;
    s.ID = 'M';
    return s;
}

The void is also not needed for empty parameters. Moreover, you need to make the type of s in main() AccountInfo as well:

int main()
{
    Account a;
    AccountInfo s = a.Operation();
}

Upvotes: 3

Steven Hansen
Steven Hansen

Reputation: 3239

Change struct to AccountInfo everywhere except for the initial declaration.

Upvotes: 1

Related Questions