Home > OS >  C Why are the changes to my class attributes in my class methods not saving?
C Why are the changes to my class attributes in my class methods not saving?

Time:03-07

I have a class that has x, y, and mass (which acts as radius) attributes. All of which are floats. I also have this method:

float shrink(float attackerMass) {
    float shrinkAmount = attackerMass * GetFrameTime();
    mass -= shrinkAmount;

    return shrinkAmount;
}

This method is called when another circle is touching the circle, and it shrinks the circle by the right amount (I put an std::cout line underneath mass -= shrinkAmount to test it) but the value of mass is never actually applied to the object. My guess is that I'm somehow changing the value of a copy of my circle object and not the actual referenced one but I have no idea how that'd be happening.

Here's the entire object class if needed (I am using functions from Raylib):

class Blib {
private:
    Color color;
    Blib* address{ this };
public:
    float x;
    float y;
    float mass;
    
    /* Constructor */
    Blib(float x, float y, float mass = 32.0f, Color color = Color{ 255, 255, 255, 200 }) {
        this->x = x;
        this->y = y;
        this->mass = mass;
        this->color = color;
    }

    /* Methods */
    void check_collisions(std::vector<Blib> blibs) { //

        for (Blib blib : blibs) {
            
            if (CheckCollisionCircles(Vector2{ x, y }, mass, Vector2{ blib.x, blib.y }, blib.mass)) {

                if (mass > blib.mass && address != blib.address) {
                    grow(blib.shrink(mass));
                }
            }
        }
    }

    void draw() {
        DrawCircle(x, y, mass, color);
    }

    void grow(float amount) {
        mass  = amount;
    }

    void move_with_keyboard() {
        float speed = 5.0f * mass * GetFrameTime();

        if (IsKeyDown(KEY_W)) {
            y -= speed;
        }

        if (IsKeyDown(KEY_A)) {
            x -= speed;
        }

        if (IsKeyDown(KEY_S)) {
            y  = speed;
        }

        if (IsKeyDown(KEY_D)) {
            x  = speed;
        }
    }

    float shrink(float attackerMass) {
        float shrinkAmount = attackerMass * GetFrameTime();
        mass -= shrinkAmount;

        return shrinkAmount;
    }
};

CodePudding user response:

Here:

for (Blib blib : blibs)

Simply change to:

for (Blib &blib : blibs)

You want a reference, otherwise you are just changing a temporary variable that disappears at the end of each for loop iteration.

PS: I usually prefer:

for (auto &blib : blibs)

PPS: Your function signature also needs to be a reference:

void check_collisions(std::vector<Blib> &blibs)
  • Related