I am having difficulty with my project. it is Library with books that can be borrowed by user.
there are three classes Library, user and Book.
Final version will have option for user to set size of the Library (lest say 10 spaces for books)
User will be able to list books pick 1 and borrow it.
Return book to Library and get another book.
I am having trouble with transferring my uniqute_ptr of Book type to Library class.
In main
1 2 3
std::unique_ptr<Book> book_ptr = std::make_unique<Book>("title", "author", 1111); // I am creating object
std::vector<Library> lib; // I am creating lib object which is a vector of type Library
lib.at(0).Add(book_ptr); // I am adding pointer of Book type to method add
In Library
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Library
{
private:
std::vector<std::unique_ptr<Book>> shelf_with_books;
public:
void Add(std::unique_ptr<Book> bk)
{ // I have tried this 3 approaches none seems to be working (comment uncomment required lines)
shelf_with_books.push_back(bk); //1 does not work
shelf_with_books.push_back(std::move(bk)); // 2 does not work
shelf_with_books.push_back(std::make_unique(bk)); // 3 does not work
}
You cannot copy a unique_ptr, only move it, so you need to use std::move when passing it to the Add function.
lib.at(0).Add(std::move(book_ptr));
Number 2 is correct inside Add.
shelf_with_books.push_back(std::move(bk));
lib is a vector of libraries but you have not added any libraries to it so lib.at(0) will throw an exception. If you only want to use one library in your program there is no need to use vector here.
Why I am unable to use push_back with lib vector?
lib.push_back(std::move(book_ptr)); // <- does not work
If lib is still a vector of libraries it doesn't work because book_ptr is not a Library.
If you have changed lib to a Library object it doesn't work because the Library class doesn't have a function named push_back.