How to use an object returned from another function?

Take a look at the very simple code below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>

using namespace std;

class Employee
{
    private:
        string ename;
        double esalary;
    public:
      Employee(string nm = "", double sal = 0.0)
      {
            ename = nm;
            esalary = sal;
      }

      string getName()
      { return ename;}
      double getSalary()
      {  return esalary;}
};

Employee read_employee();
int main()
{
    read_employee();
    
    cout << r.getName << endl; // this does not work, obviously
    cout << r.getSalary << endl; // this does not work, obviously

    return 0;
}


Employee read_employee()
{
    string name;
    cout << "Please enter the name: ";
    getline(cin, name);
    double salary;
    cout << "Please enter the salary: ";
    cin >> salary;
    Employee r(name, salary);
    return r;
}


I want to be able to call the read_employee function from main, and then print out the values of the member variables FROM MAIN. I'll need the object to access the member variables, so how can I use the object returned from read_employee() in main?

NOTE: This is WITHOUT overloading any operators.

Is there a way to do this?
Last edited on
If you make read_employee() return a reference, you can:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Employee& read_employee()
    {
    string name;
    cout << "Please enter the name: ";
    getline(cin, name);
    double salary;
    cout << "Please enter the salary: ";
    cin >> salary;

    static Employee r( name, salary );

    return r;

    }
To use an object returned from a function, you have to not ignore it. ;)

1
2
3
4
5
6
7
8
9
int main()
{
    Employee r = read_employee();
    
    cout << r.getName() << endl; // this does not work, obviously
    cout << r.getSalary() << endl; // this does not work, obviously

    return 0;
}


koothkeeper wrote:
If you make read_employee() return a reference, you can:

Not a good idea.
Last edited on
@cire: Wow, I feel really stupid with this one, lol. I was missing the open-close parenthesis, but the this whole time I thought the assignment statement was not working. Ugh...

Thank you.
Topic archived. No new replies allowed.