1

i have a class book and 2 subclass lerningbook,readingbook and i am trying to create a list of books book* listofbooks and add to it the subclass

Book* listOfBooks;

void Mang::addBookToList(Book b3)
{
    Book* temp;
    temp=listOfBooks;
    lobsize++;
    listOfBooks=new Book[lobsize];
    int i;
    for(;i<lobsize;i++)
    {
        listOfBooks[i]=temp[i];
    }
    listOfBooks[i]=b3;
}

problem is when i am trying to send it the subclass this not accpecting it i tryed to use template so the function will be able to take any class but it didnt help
the error am geting is:
no suitable user defined conversion from lerningbook to book exsists
guessing i need to implement same type of function that will allow me to do this but i dont know wich one hope one of you can help me out thx in adv :)
(i know i am missing the delete[] on the temp array sort of got stuck on this problem)

1 Answer 1

1

b3 is a Book, but listoOfBooks is an array of Book*. You need to pass a Book* to addBookToList, not just for the assigment but to avoid object slicing.

If this is not a learning exercise, use a std::vector<Book*> instead or a std::vector<std::shared_ptr<Book>>. The std::vector will dynamically grow as required and the use of a smart pointer will automatically delete the elements when the vector is destroyed.

If you choose use of the Book* ensure you obey the What is The Rule of Three?. This could just be making Mang non-copyable by declaring the copy constructor and assignment operator private.

Note that i is uninitialised in for loop and the following assignment is out of bounds access on the array as i == lobsize after the for:

listOfBooks[i]=b3;

array indexes run from 0, so lobsize - 1 is the index of the last element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.