When you write a member function that doesn’t modify the object it operates on, please make sure to make it const.
class Whisky {
public:
Smell smellIt() const;
Tase tasteIt(int ml);
};
Smelling the whisky doesn’t modify it, so I made smellIt() const. Tasting does however modify it (there is less left in the glass), so tasteIt() is not const.
Why does this matter? If someone makes a const object of the class, they might still want to call some methods on it. For instance, a good practice for a method is to take objects by reference to const. And then you will only be able to call const methods:
void describeWhisky(const Whisky& whisky) {
std::cout << whisky.smellIt();
}
This would not be possible if smellIt() was not const. The same goes for using const_iterators and a lot of other situations, so please remember to add const whenever you can, even though it doesn’t make a differece to you then and there.
Edit: I posted a follow up, on how you can change some parts of an object, even if it is const.
Discover more from C++ on a Friday
Subscribe to get the latest posts sent to your email.
Thanks for the nice post. I use to think using const was a hassle but this made me realise why it is useful.