Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;


    public:
    particle(float radius,int x, int y)
    {
        setRadius(radius);
        setOrigin(radius, radius);
        setPosition(x, y);
        setFillColor(sf::Color::White);
        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)
    {
        p.update_pos();
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading