+ 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

10th May 2021, 7:02 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
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.
10th May 2021, 7:20 PM
Schindlabua
Schindlabua - avatar