C++
Checking out
Write the checkout flow with checkout and return methods.
Checking out
The core function of a library is checking out books. The checkout(int idx) method checks out a specific book: first it checks whether the index is valid and the book is available, then sets borrowed[idx] to true and returns true.
Two conditions are checked: idx < 0 || idx >= (int)books.size() for out of bounds, and borrowed[idx] for already borrowed. In both cases it returns false. With this design the same book cannot be checked out twice. The borrowed vector is initialized to false during addBook.
Availability check
The checkout method returns false in two cases: invalid index or an already borrowed book. This lets the caller react based on the result. With if (lib.checkout(0)) you print a message when the checkout succeeds.
We take the previous lesson's Library class and add the checkout method. The borrowed vector was already initialized to false during addBook. So no new field is needed; we only add a new method. This is the power of cumulative design.
Exercise Add the checkout method
Take the previous lesson's Book and Library classes. Add bool checkout(int idx) to Library: it returns false for an invalid index or an already borrowed book, otherwise sets borrowed[idx] = true and returns true. In main, check out book 0 and print "out" on success.
Show example solution
#include <iostream>
#include <string>
#include <vector>
class Book {
private:
std::string title;
std::string author;
public:
Book(std::string t, std::string a) : title(t), author(a) {}
std::string getTitle() const { return title; }
std::string getAuthor() const { return author; }
};
class Library {
private:
std::vector<Book> books;
std::vector<bool> borrowed;
public:
void addBook(const Book& b) { books.push_back(b); borrowed.push_back(false); }
size_t count() const { return books.size(); }
Book getBook(int idx) const { return books[idx]; }
bool checkout(int idx) {
if (idx < 0 || idx >= (int)books.size()) return false;
if (borrowed[idx]) return false;
borrowed[idx] = true;
return true;
}
};
int main() {
Library lib;
lib.addBook(Book("Tutunamayanlar", "Oğuz Atay"));
lib.addBook(Book("İnce Memed", "Yaşar Kemal"));
if (lib.checkout(0)) {
std::cout << "out";
}
return 0;
}
Test yourself
-
Match each condition to its purpose
- idx < 0
- Negative index
- idx >= books.size()
- Out of bounds
- borrowed[idx]
- Already borrowed
- borrowed[idx] = true
- Mark as borrowed
-
Complete the marking line
if (borrowed[idx]) return false;
____[idx] = true;
return true;
Show answer
if (borrowed[idx]) return false;
borrowed[idx] = true;
return true;
-
What does the checkout method do?
bool checkout(int idx);
- Checks out a book
- Removes a book
- Counts books
- Adds a book
Show answer
Checks out a book — checkout checks out a book and marks it as borrowed.
Next lesson: Search and filter