Reputation: 11
class Student
{
Book* m_book[8];
public:
Student()
{
for ( int i = 0; i < 8; i++){
m_book[i] = NULL;
}
}
~Student()
{
for ( int j = 0; j < 8; j++){
delete m_book[j];
}
}
void addBook(Book& book)
{
int k = 0;
while(m_book[k] != NULL){
k++;
}
Book book = new m_book[k];
}
};
Why is the addBook
member function not working?
Upvotes: 0
Views: 68
Reputation: 63402
There are many things wrong with the line Book book = new m_book[k];
pointer to type
to a Book, which is invalidoperator new
on the value m_book[k], not a typeYou also have an array of book pointers, with ownership semantics. You don't need the pointers, you could just have an array of Books directly.
A much simplified Student:
class Student
{
std::array<Book, 8> m_books;
size_t count = 0;
public:
void addBook(const Book & book)
{
m_book[count] = book;
++count;
}
}
No pointers, default constructor, default destructor
Upvotes: 1
Reputation: 7542
Book book = new m_book[k];
should be
m_book[k]=new Book(book);
Upvotes: 0