1
votes

I've been stuck on this one problem all day and maybe someone can explain it to me? I'm not providing my exact code, but a similar situation of what I'm trying to accompish (and the shortened version). It's a restaurant simulator.

int main() {
    Restaurant i;
    string tableID;
    cin >> tableID;
    i.append(new Table(tableID));//this appends a new table to the linked list
}
//.h file we're not allowed to modify
class Table
{
public:
    Table(const string& tableID);//constructor
private:
    string* tableID;
}
// .cpp file I'm writing
Table::Table(const string& tableID){
    this->tableID = tableID;
}

I'm getting the error:

table.cc:9:18: error: cannot convert ‘const string {aka const std::__cxx11::basic_string}’ to ‘std::__cxx11::string* {aka std::__cxx11::basic_string*}’ in assignment this->tableID = tableID;

Can anyone tell me what's going on? To me it seems like it's passing the address of tableID in main() and assigning it to a pointer in the constructor, which I thought was legal but maybe it's the const throwing me off.

1
Well, the error message seems pretty clear. You are trying to assign an expression of type string to a variable of type "pointer to string". It doesn't work for the same reason int* p = 42; wouldn't work - neither makes sense. - Igor Tandetnik
Yeah I figured that was it, but i couldn't figure out how I'm gonna convert that string to pointer. - Mike1982

1 Answers

1
votes

Several options:

  1. Change the definition of tableID in class Table to be string tableID. In this case you'll keep a copy of the value in the instance.

  2. Change the assignment to this->tableID to be this->tableID = &tableID. In this case you'll assign the address of the tableID parameter to this->tableID. In this case you'll only keep a pointer to the table name in the instance, which could cause some interesting behavior. You'll probably learn the most with this approach.

  3. Change the assignment to this->tableId = new string(tableID). Here you're allocating a new string, populating it with the value of the parameter tableID, and then assigning the address of the new string to the instance var tableID. But because you don't have a destructor defined for this class you'll leak this allocated string every time you destroy an instance to Table.

Perhaps some combination of the above would be best.

Best of luck.