I have an object Room and each Room has an array of 4 references to other rooms
header file:
namespace test
{
class Room
{
public:
Room* references[4];
void Connect(Room roomReference) const;
}
}
and in my cpp file, I am attempting to attach that reference by inserting the pointer of the room to a specific index in references. However, I get the following compiler error "Cannot assign to readonly type Room* const." But when I create a local variable of the same type and insert into there, it works.
void Room::Connect(Room roomReference) const
{
Room* roomReferenceItem = &roomReference;
Room* foos[4];
// This works
foos[2] = roomReferenceItem;
// This does not
this->references[2] = roomReferenceItem;
}
I am not sure if there is some misunderstanding I am having with global arrays in C
CodePudding user response:
You declared a constant member function
void Connect(Room roomReference) const;
So you may not change data members of the class because in this case the pointer this
is defined like const Room *
.
Remove the qualifier const
from the function declaration.
Also you must pass an object of the type Room
by reference to the function as for example
void Connect(Room &roomReference);
Otherwise pointers stored in the array references
will be invalid because they will point to non alive temporary objects after exiting the function.
CodePudding user response:
The array isn't global, but that's not where the problem is. Room::Connect
is marked const
, so it cannot modify the contents of references
. So get rid of the const
. And then the problem will be that roomReference
is an object that will go away when the function returns, so storing a pointer to it won't accomplish anything good. Change it to Room& roomReference
.