Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying private class variables within a class method?

This is probably a really basic error I'm making, but I'm quite new to c++ so please don't judge!

Basically, I've got two classes as follows:

class A{
    private:
    vector< vector<int> > images;

    public:
    int f1(int X, int Y);
}

class B{
    private:
    int x;
    int y;

    public:
    int f2(A var);
}

I want to be able to call B.f2(A) with defined variables A and B and have f2() call A.f1(x,y). So far, all this works. But the function f1 assigns values to the vector 'images' which aren't there when f2() returns. Any ideas why? Here's the code:

int A::f1(int X, int Y){
    // Some stuff to resize images accordingly
    images[X][Y] = 4;
    return 0;
}

int B::f2(A var){
    var.f1(x, y);
    return 0;
}

int main(){
    A var1;
    B var2;

    // Stuff to set var2.x, var2.y
    var2.f2(var1);

    // HERE: var1.images IS UNCHANGED?
}
like image 973
eigensheep Avatar asked Nov 16 '25 17:11

eigensheep


1 Answers

this is because you have passed A by value. instead, pass it by reference.

void fn(A& p);
         ^ << refer to the original object passed as the parameter.

as it is now, your program creates, and then mutates a copy of var1.

when you do not want to mutate the parameter, you can pass it as a const reference:

void fn(const A& p);
        ^^^^^  ^
like image 124
justin Avatar answered Nov 19 '25 08:11

justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!