2

in my class, I have two methods that are responsible for getting and setting the value of a private variable. In another method that is outside of the class, I call the setter method and change the variable to another value. It works temporarily but always resets to the original value.

class storeItem
{
    public:
        void setPrice(int p)
        {
            price = p;
        }
        int getPrice()
        {
            return price;
        }
        storeItem(int p)
        {
            price = p;
        }
    private:
        int price;
}

void changePrice(storeItem item)
{
    int origPrice = item.getPrice();
    item.setPrice(rand() % 10 + 1);
    //The price is correctly changed and printed here.
    cout << "This item costs " << item.getPrice() << " dollars and the price was originally " << origPrice << " dollars." << endl;
}

int main()
{
    storeItem tomato(1);
    changePrice(tomato);
    //This would print out "This item costs *rand number here* dollars and the price was originally 1 dollars." But if I call it again...
    changePrice(tomato);
    //This would print out "This item costs *rand number here* dollars and the price was originally 1 dollars." even though the origPrice value should have changed.
}

I'm sure I'm making a silly beginners mistake and I appreciate any help in advance! :)

Heckel
  • 428
  • 9
  • 23

2 Answers2

5

In C++, function parameters are passed by value unless you indicate otherwise. In your example, you are passing the storeItem by value to your function, so you are modifying a local copy inside of the function body. There is no effect on the caller side. You need to pass a reference:

void changePrice(storeItem& item)
                          ^

Semantically, a reference is just an alias for an object, so you can consider the storeItem inside of your function to be the same as the one on the caller side.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

When calling your function changePrice you don't call it by reference, nor with a pointer to the storeItem, so a copy is built.

Call it by reference instead:

void changePrice(storeItem& item)
{
     //what you did before
} 

Refer to this for further reference.

Theolodis
  • 4,977
  • 3
  • 34
  • 53