Saturday, January 2, 2021

Declare const functions in cpp

 I was writting some code in c++ and I ran in to following issue with keyword const. At that point I realised that my knowledge about usage of const in C++ is very low. Here I'm writing this post with things I leaned after this mistake.

This is a simple Message class and I tried to override it's operator < so that it will be easier for sorting a container with Message objects. 


I got following error after compiling full code.


After a quick search with the help of google I found this SOF answer and according to that reason for error is, I'm calling non-const function getId which doesn't promise not to modify const Message object.

But as you can see, I had used const keyword with function getId. Guess what.. ! it is a wrong usage. It return a constant integer and return value cannot be changed. But here what I wanted is a function that gurantee calling object's safety. For that we'll have to use the const keywaord after the parameter list of function declaration.

This SOF question contains some nice explanations about the difference between const positioning with function declarations.



Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...