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

StackOverflow https://stackoverflow.com/questions/8483767

  •  14-03-2021
  •  | 
  •  

Question

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

Was it helpful?

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.

OTHER TIPS

If you have declared something is const, just like you make a promise to the compiler, you will never change the content in that thing, why would you want to do that?

If you really want to change something in the const type, you have to declare that mutable:

class A
{
public:
mutable int _change_me;
};

Now you can change the member _change_me even you have a const reference for class A.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top