Trying to instantiate a class member in C++ with a variable name
- by MarcZero
Hello. 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.