Reid
Reid

Reputation: 1129

Passing a vector by reference to function, but change doesn't persist

I'm new to C++ so please forgive the noob question. In my program, I pass a vector of "Employee" objects to a function by reference, which calls an Employee member function on each object in the vector, to raise "salary" by "r" percent (in this case 2 percent). I've verified that this is happening by logging the call (the salary is changed within the function), but the changes don't persist...when I print the Employee objects again, the salaries are unchanged. Appreciate any help!

// main.cpp
void raiseAllBy2Percent(vector<Employee> &v)
{
for (int i = 0; i < v.size(); i++)
    {
    Employee e = v[i];
    e.salaryRaise(2);
    }
}

// Employee.cpp
void Employee::salaryRaise(double r)
{
cout << "**salaryRaise called";
_salary += (r/100 * _salary);
cout << "**new salary: " << _salary; // This logs with the change as expected
}

Upvotes: 13

Views: 29013

Answers (3)

user529758
user529758

Reputation:

You are passing the vector by reference, but at this line:

Employee e = v[i];

you are copying the employee object. Make that a reference too:

Employee &e = v[i];

and it will behave as expected.

(Note that this only works because std::vector::operator[] itself returns a reference, as most standard containers' subscript operator does.)

Upvotes: 18

juanchopanza
juanchopanza

Reputation: 227418

You are making a copy of the elements in the vector here:

Employee e = v[i]; // e is a copy of v[i]

You probably mean

v[i].salaryRaise(2);

Upvotes: 2

digital_revenant
digital_revenant

Reputation: 3324

You are not changing the vector content. Instead you assign it to another new Employee object, e and modify that:

Employee e = v[i];
e.salaryRaise(2);

Change this to:

v[i].salaryRaise(2);

This will modify the elements in the vector.

Upvotes: 4

Related Questions