tmricks94
tmricks94

Reputation: 35

Invalid conversion from 'int' to 'const char*' issue C++

The problem occurs in my ToDoList.cpp class file.

ToDoList.cpp:

ToDoList::ToDoList() {
    arraySize = 3;
    arrayData = 0;
    array = new string(arraySize); //error here
}
ToDoList::ToDoList() {
    array = new string(todolist.arraySize); //and error here
    arraySize = todolist.arraySize;
    arrayData = todolist.arraySize;
}

ToDoList.h:

class ToDoList {
public:
    ToDoList();
    ToDoList(const ToDoList&);
    ~ToDoList();
    void AddItem(string item);
    void ListItems();

private:
    string* array;
    int arraySize;
    int arrayData;
};

Upvotes: 0

Views: 1317

Answers (3)

Mantosh Kumar
Mantosh Kumar

Reputation: 5741

You should use

array = new string[arraySize];

and

array = new string[todolist.arraySize];

In your example, you are trying to create an object of std::string class(string(arrraySize)) which is not valid. Compiler is giving the appropriate error to understand it.

EDIT

Your class may be written using std::vector which is efficient correct and easy to understand code.

class ToDoList {
public:
    ToDoList() {};
    ~ToDoList() {};
    void AddItem(std::string& item);
    void ListItems();
private:
    std::vector<std::string> array;
};

void ToDoList::AddItem(std::string& item) {
    array.push_back(item);
}

void ToDoList::ListItems() {
    for(size_t i = 0; i<array.size(); i++) {
        std::cout<<array[i]<<std::endl;
    }
}

Upvotes: 2

sj0h
sj0h

Reputation: 912

There's no std::string constructor with just a length. If you want to initialise a string with something in it, you need to say what characters to use. You could use new string(arraySize, fillCharacter), but given this usage, maybe std::vector may be more appropriate.

Edit: the extra details shows you are trying to do something different. So see the other answers. However it looks like you are trying to re-invent a vector<string> , so you may find it easier to use a std::vector instead of manually allocating your array of strings.

Upvotes: 1

The Dark
The Dark

Reputation: 8514

If you want an array of strings, use

array = new string[arraySize];

Upvotes: 1

Related Questions