class member values doesn't get changed by function… "noob question"

I am trying to update the particles positions by calling a function for the class..
The values for v_x, v_y, a_x, a_y doesnt keep its new value after the function. I thought this would work because update_pos is a member function of the class.
what am i doing wrong here?

class particle : public sf::CircleShape
    float mass;
    float v_x, v_y, a_x, a_y;

    particle(float radius,int x, int y)
        setOrigin(radius, radius);
        setPosition(x, y);
        mass = radius;

        v_x = 0;
        v_y = 0;
        a_x = 0;
        a_y = 0;

    void update_pos()
        float g = 9;

        //upd acc
        a_x += g * 0 / mass;
        a_y += g / mass;
        //upd vel
        v_x += a_x;
        v_y += a_y;

        //move particle
        setPosition(getPosition().x + v_x, getPosition().y + v_y);

this function is used in main to update every particle.

void update_particles(std::vector<particle>& particles)
    for (particle p : particles)

>Solution :

This code

for (particle p : particles)

copies every particle in your vector, p is a copy. So you are changing copies of the particles in your vector, not the originals.

To avoid the copy you need a reference

for (particle& p : particles)

For a largish class like particle a reference is desirable anyway, just for efficiency reasons.

Leave a Reply