I have this array of "Table" objects.
Table tables[25];
Inside this object there is this constant variable
const int maxSize;
The constructor looks as follows:
Table::Table(int tblid, int mseats) : maxSeats(mseats) {
tableId=tblid;
status=IDLE;
}
I get an error when trying to add an object to this array where both tableID and maxSeats are integers.
tables[tableID]=Table(tableID,maxSeats);
This is the error I get:
Table.h: In member function ‘Table& Table::operator=(const Table&)’:
Table.h:11: error: non-static const member ‘const int Table::maxSeats’, can't use default assignment operator
hw4.cpp: In function ‘int main()’:
hw4.cpp:66: note: synthesized method ‘Table& Table::operator=(const Table&)’ first required here
However when I remove the const from the variable declaration in the class it works fine.
Is there any way I can add objects to this array without removing the constant from the variable declaration?
I'm assuming that you haven't defined your own operator= in your Table class, so it will attempt to generate one for you by just using the regular operator= on every member variable, but as one of your members is const it cannot be assigned that way it must be initialised upon its construction, so define your own operator= for your Table class which creates a Table object constructed with a copy constructor and returns it.
Hope this makes sense, if you don't understand I'll give you an example
Something like this?
Table& Table::operator=(const Table &rhs) {
Table(rhs.getId(),rhs.getSize()); ->I'm not quite sure about this line; I do have those two getter methods but I don't know if that's the right way to assign it.
not quite like that no, firstly you'll have to return a Table object, not a reference to a Table, as you'll end up returning a reference to a local object which goes out of scope and is destroyed when the function exists, so instead of that just return the object itself.
You're also not using a copy constructor like I suggested, but what you do there would work as long as you have that constructor for Table which takes two parameters and initialises the const member
EDIT - Forgot, you also return *this in your overloaded operator, you should be returning a new Table object not *this