1
void set_fee(Patron p, int fee)
{
    for (Patron x : patrons)
    {
        if (p.get_name() == x.get_name()) x.set_fee(fee);
    }
    
    for (int i = 0; i < patrons.size(); i++)
    {
        if (patrons[i].get_name() == p.get_name()) patrons[i].set_fee(fee);
    }
}

So patron is just some class I made and none of the functions here really matter get_name() just returns the object's name and set_fee(fee) just sets the fee of the object to fee.

But does anyone have any idea for why the first loop doesn't work but the second one does? I basically just wanna look for p inside the patrons vector and once I find it I want to change the fee of the patron object inside the vector, but the first way doesn't work, why?

JeJo
  • 30,635
  • 6
  • 49
  • 88
yaelreshet11
  • 131
  • 5
  • 4
    You probably want reference instead of copy: `for (Patron& x : patrons)` – Jarod42 Nov 02 '21 at 15:26
  • 1
    @yaelreshet11 The copy constructor may be working just fine, but `x.set_fee(fee);` is not working on the object you have in `patrons` but on the copy you have in `x`. – Ted Lyngmo Nov 02 '21 at 15:29
  • @yaelreshet11 No, it probably means that the copy constructor works. If you modify a copy, it's typically desirable that only the copy is affected and not the object that was copied from. – eerorika Nov 02 '21 at 15:29
  • Also note that if `p` does not change inside the function, you can pass by `const` reference: `void set_fee(Patron const& p, int fee)` – Const Nov 02 '21 at 15:33

1 Answers1

9

Your x in the range based for loop is a copy of the element in the vector. You need to have reference there

for (Patron& x : patrons)
//   ^^^^^^^^
{
   // ....
}

or else x.set_fee(fee); will be called on the copy.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
JeJo
  • 30,635
  • 6
  • 49
  • 88