1

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++

1
  • 3
    Two problems, Connect is const so it can't modify member variables. roomReference is a local variable which will be destroyed when the function exits leaving you with a dangling pointer to an invalid object. Commented Sep 4, 2022 at 21:40

2 Answers 2

5

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.

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

3 Comments

OMG lifesaver! I spent waaaay too much time on this. Thanks!
@RobertMichaelWatson The thing I'm wondering about is why you declared the function as const in the first place. Normally we see beginners failing to declare as const functions that should be const, not the other way around.
Lol goot question. It was actually Resharper for C++ that suggested I switch it
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.