+ 1
Use of const cast
Please refer code below: I have created a non const object which is passed to method asking for const as well as non const object Same way, another object which is const object is passed to both method asking const and non const object as argument. If all these four works without const cast, why i.e. where it is required? https://code.sololearn.com/c2gXefaGV3jO/?ref=app
1 Answer
+ 3
You don't see errors here because you are passing by value. Of course if you are copying a const value you can modify the copy as much as you wishâcopying a `const test` into a `test` is not a problem.
If instead you are dealing with references, like:
void display1(test& obj) { ... }
void display2(const test& obj) { ... }
You'll see an error:
error: no matching function for call to 'display1'
display1(obj1);
^~~~~~~~
note: candidate function not viable: 1st argument ('const test') would lose const qualifier
void display1(test& obj)
Dropping the const qualifier like that would mean the display1 function can modify your const object which mustn't happen.
So that's when you'd use const_cast to drop the const explicitlyâbut only if you know it is safe to do so of course. If it's not it can crash your program.