13

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
}
Reid
  • 1,109
  • 1
  • 12
  • 27
  • Alright, as I suspected a simple fix. Making a local copy of "Employee" was of course the problem. I wish I could mark multiple answers as accepted...but you all got upvotes. Thanks!!! – Reid Oct 26 '13 at 16:13

3 Answers3

18

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.)

4

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.

digital_revenant
  • 3,274
  • 1
  • 15
  • 24
2

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);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480