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! :)