Search code examples
c++memoryheap-memoryallocation

Creating objects on the heap through a class function


   Book book;
list<Book>* books;

string title;
string author;
int ISBN;

     Book* Administrator::addBook()
{
    Book *newBook = new Book();
    cout << "Would you like to enter a book?" << endl;
    cin >> userInput;
    cout << endl;

    if (userInput == "yes")
    {

        cout << "What is the title of the book you want to enter?" << endl;
        cin >> title;

        cout << "What is the author of the book you want to enter?" << endl;
        cin >> author;

        cout << "What is the ISBN of the book you want to enter?" << endl;
        cin >> ISBN;

        cout << endl;

        newBook->setTitle(title);
        newBook->setAuthor(author);
        newBook->setISBN(ISBN);
        newBook->setAvailability(true);

        books->push_back(*newBook);

    }
    return newBook;
}

Here im creating my book objects in my Administration class, the problem im having is when i try and access them from another class, its says they are not there.

I did a bit of reading and understand I've to allocate the objects to the heap using dynamic memory management, is there a way i can do this within my code?

Any help would greatly be appreciated.


Solution

  • Here's a simple way:

    if (userInput == "yes")
    {
       Book *newBook = new Book(); // <-- allocates a Book object on the heap
       cout << "What is the title of the book you want to enter?" << endl;
       [...]
       newBook->setTitle(title);
       [...]
       return *newBook;
    }