Search code examples
c++oopconst-cast

How to get a const reference to an object and change the object using that reference (Using const_cast)?


I have a member function returning a const reference to an instance of a class.

Example:

class State
{
  const City* city1;
public:
  State(const City& c) : city1(c) {}
  const City& getReference() const {return *city1;}
  void changeStuff();
};

How do I get a non-const City * pointing to city1 using const_cast and getReference()?

Also, by doing the following I was able to achieve what I wanted without using const_cast: (Assuming there is already an instance of State called state1)

City ref = state1.getReference(); //Why does it work?
City * ptr = &ref; //This is what I wanted, but not this way
ref->changeStuff(); //How can I call functions changing things if the reference was constant?

How am I able to get a non-const reference from a function returning a const reference and even call setters?

Thanks for your attention


Solution

  • City ref = state1.getReference(); //Why does it work?
    

    It works because that's not a reference. You're making a copy of the const value. Try this:

    City & ref = state1.getReference();
    

    That won't work. You can use const cast like this:

    City * ptr = const_cast<City*>(&state1.getReference());
    

    Just be sure that the object isn't really const. Otherwise it's undefined behavior to actually try to modify it.