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)
b3is aBook, butlistoOfBooksis an array ofBook*. You need to pass aBook*toaddBookToList, not just for the assigment but to avoid object slicing.If this is not a learning exercise, use a
std::vector<Book*>instead or astd::vector<std::shared_ptr<Book>>. Thestd::vectorwill dynamically grow as required and the use of a smart pointer will automaticallydeletethe elements when thevectoris destroyed.If you choose use of the
Book*ensure you obey the What is The Rule of Three?. This could just be makingMangnon-copyable by declaring the copy constructor and assignment operatorprivate.Note that
iis uninitialised inforloop and the following assignment is out of bounds access on the array asi == lobsizeafter thefor:array indexes run from 0, so
lobsize - 1is the index of the last element.