Search code examples
c++variablesupdating

Updating value of class variables - C++


I'm just beginning to learn how to code and I've come across a problem I can't seem to solve. More specifically the problem occurs in the "borrows" function.

In the following program I am somehow unable to update the value of the public class variable "stock" even though I used getters and setters. It seems to be updated correctly on the cout right after but not "saved permanently". My guess is that it's modifying a copy of the variable rather than the variable itself.

I have attached my code to the post! Please let me know if I should upload the whole file!

Thanks in advance!

void Book::borrows() {
    int searchid;
    bool isfound=false;
    cout<<"Please enter the unique ID of the book:\t\t";
    cin>>searchid;
    for(auto i:myBooks){
        if (i.id==searchid){
            cout<<"This book matches your search:\t"; print(i);
            if (i.stock==0) {
                cout<<"Book is out of stock!"<<endl;
            } else {
                setStock((i.stock-1));
                cout<<"Successfully borrowed!! Now there are only "<<getStock()<<" copies left in stock!"<<endl;
            }
            isfound=true;
        }
    }
    if (isfound== false){
        cout<<"++++\t\tBook not found++++\t\t"<<endl;
    }
    system("pause");
}

int Book::getStock() const {
    return stock;
}

void Book::setStock(int newstock) {
    Book::stock = newstock;
}

Edit 1:

Here is my Class structure and my vector:

class Book{
public:
    int id;
    string title;
    int stock;

    void add();
    void displayall();
    void displayspecific();
    void print(Book);
    void borrows();
    void returns();

    int getStock() const;

    void setStock(int stock);
};

vector<Book> myBooks;

Solution

  • Your actual problem is that you are operating on a copy of the Book object, not the setters and getters of the members of a book.

    for(auto i:myBooks){
    

    You need

    for(auto &i:myBooks){
    

    But as other have pointed out, you need 2 classes, Library and Book.