T.S.
T.S.

Reputation: 11

new operator help, type-specifier and other errors

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

Answers (2)

Caleth
Caleth

Reputation: 63402

There are many things wrong with the line Book book = new m_book[k];

  • You are trying to assign a pointer to type to a Book, which is invalid
  • You are using operator new on the value m_book[k], not a type

You 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

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

   Book book = new m_book[k]; 

should be

   m_book[k]=new Book(book);         

Upvotes: 0

Related Questions