Passing a vector by reference to a function, but the change is not saved

I am new to C ++, so please excuse the noob question. In my program, I pass the Employee object vector to a function by reference, which calls the Employee member function for each object in the vector to increase the "salary" by "r" percent (in this case, 2 percent). I checked that this happens by registering a call (the salary changes inside the function), but the changes are not saved ... when I print Employee objects again, the salaries remain 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 } 
+7
c ++ pass-by-reference vector
source share
3 answers

You pass the vector by reference, but in this line:

 Employee e = v[i]; 

You are copying an employee object. Make also a link:

 Employee &e = v[i]; 

and he will behave as expected.

(Note that this only works because std::vector::operator[] returns a link, as most index container standard operators do).

+11
source share

You do not change vector content. Instead, you assign it to another new Employee , e object and modify this:

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

Change this to:

 v[i].salaryRaise(2); 

This will change the elements in the vector.

+3
source share

You make 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); 
+1
source share

All Articles