What is the best example of a const function which is remarkable because of const keyword? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the best example of a const function which is remarkable because of const keyword?

Give the code please 🙂

17th Jun 2018, 2:13 AM
Rounak Sartaliya
Rounak Sartaliya - avatar
1 Answer
+ 2
In C++ you should make everything const unless you have a good reason not to; not the other way around. It's really just helping the programmer. const functions let you know that after calling them, the object is in the same state as before. Silly example but maybe you have a complex class and you write a void MyClass::pretty_print( ) const { cout << ... } that prints some information to the console. You wouldn't expect this function to change the object so there is no reason not to make it const. Try it in your next program - make all the functions const unless the compiler complains. It will work out more often than not.
17th Jun 2018, 2:37 AM
Schindlabua
Schindlabua - avatar