I am writing a program for class that is asking us to create a class of “book”. We are then supposed to create new instantiations of that class upon demand from the user. I am new to C++ so I am attempting to code this out but am running into a problem.
The main problem is how do I instantiate a class with a variable if I don’t know how many I will have to do ahead of time. The user could ask to add 1 book or 1000. I am looking at this basic code:
This is the simple code I started with. I wanted to have an index int keep a number and have the book class I create be called by that int (0, 1, 2, etc…) So I attempted to convert the incoming index int into a string, but I’m kind of stuck from here.
void addBook(int index){
string bookName;
std::stringstream ss;
ss << index;
book bookName;
cout << "Enter the Books Title: ";
cin >> bookName.title;
}
But obviously this doesn’t work as “bookName” is a string to the computer and not the class member I tried to create.
All of the tutorials I have seen online and in my text show the classes being instantiated with names in the code, but I just don’t know how to make it variable so I can create any amount of “books” that the user might want. Any insight on this would be appreciated. Thank you for your time.
Given your type
book, if you want to create a list of books, try using a container likestd::vector,std::listorstd::deque.You can create books and add to the library from a loop, which sounds like what you want.
Your choice of container type will depend on the access pattern you want. For example, a
std::vectoris good if you want to add books like this and you rarely want to remove them in an arbitrary order. It’s fairly straightforward to change the type later if you change your mind about this.