1

In the code below, I am trying to use a for loop to initialise the member Name of five objects of the class book using names taken from the string array Array (numbers in this case for testing purposes).

#include <iostream>
#include <string>
using namespace std;

class book
{
private:
    string Name;
public:
    book();
    book(string&);
};

book :: book()
{}

book :: book(string& temp)
{
    Name = temp;
}

int main()
{
    string Array[] = {"1", "2", "3", "4", "5"};
    book *BookList = new book[5];
    for (int count = 0; count < 5; count ++)
    {
        BookList[count] = new book(Array[count]);
    }
    return 0;
}

However, whenever I try to compile the code, I get the following error:

main.cpp: In function ‘int main()’:
main.cpp:28: error: no match for ‘operator=’ in ‘*(BookList + ((unsigned int)(((unsigned int)count) * 4u))) = (operator new(4u), (<statement>, ((book*)<anonymous>)))’
main.cpp:6: note: candidates are: book& book::operator=(const book&)

My intention is to create an array of objects using private member values that will only be known once the loop collects the relevant data. I'm following the advice offered in answer #2 to a question I asked here previously.

2
  • It seems that you are making a BookList array and trying to initialize it with book objects. Commented Feb 17, 2011 at 23:53
  • You have to write a seperate setter method to intialize the member variable Name. Commented Feb 17, 2011 at 23:56

2 Answers 2

5
book *BookList = new book[5]; 

BookList is an array of five book objects.

BookList[count] = new book(Array[count]); 

You are trying to use BookList as if it were an array of five pointers to book objects.

BookList[count] is not a pointer to the countth book, it is the countth book.

Have you considered using one of the Standard Library containers, like std::vector?

std::vector<book> BookList(5);

or, if you don't want to insert books until you know what they are, you can create it with an initial size of 0 (by removing the (5) initializer) and push_back or insert books as you need to.

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

Comments

0
BookList[count] = new book(Array[count]);

You are essentially doing: book = book* which will obviously not work, since they are different types. You can drop the new keyword:

BookList[count] = book(Array[count]);

This will create a temporary book object, and assign it to one of the books in BookList.

Comments

Your Answer

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