Home > Software engineering >  Cannot change class objects within vector
Cannot change class objects within vector

Time:02-13

I'm having difficulties with understanding how to change the value of a class object which is stored in a vector. From the example below, I thought the case would be that "ferrari" would be yellow after I change the color, however it is still black.

From what I understand this has to do with that I'm making a new copy of vector each time and therefore not changing the object I want. I have read that it might help to write the vector like a reference instead like so: vector<Car> &cars;, but this gives an error "reference variable 'cars' requires an initializer" which I don't understand how to solve.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Car
{
public:
    string brand;
    string color;
    Car(string brand, string color)
        : brand(brand), color(color)
    {
    }
    // setter
    void setColor(string newColor)
    {
        color = newColor;
    }
};


int main()
{
    vector<Car> cars;
    cars.push_back(Car("bmw", "blue"));
    cars.push_back(Car("tesla", "red"));
    cars.push_back(Car("ferrari", "black"));

    for (Car car : cars)
    {
        if (car.brand == "ferrari")
        {
            car.setColor("yellow");
        }
    }

    for (Car car : cars)
    {
        cout << car.brand << " " << car.color << endl;
    }

    return 0;
}

CodePudding user response:

In for (Car car : cars), car is a copy of the corresponding vector element. Changing the copy doesn't affect the original.

Use for (Car &car : cars) if you want to modify the elements. Even if you only want to read (print) them, use for (const Car &car : cars) to avoid the unnecessary copy that you're currently making.


Also note that your constructor and setter are suboptimal. They need some std::moves:

class Car
{
public:
    string brand;
    string color;
    Car(string brand, string color)
        : brand(std::move(brand)), color(std::move(color))
    {
    }
    // setter
    void setColor(string newColor)
    {
        color = std::move(newColor);
    }
};

CodePudding user response:

In your for loop:

for (Car car : cars)

So when it loops, it will make a copy of the cars elements, not the element itself.

Change that to

for (Car &car : cars)
  • Related