Please Make Member Functions Const Whenever Possible


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.

Posted in C++. Tags: . 4 Comments »

4 Responses to “Please Make Member Functions Const Whenever Possible”

  1. Changing the Unchangeable « C++ on a Friday Says:

    […] week I asked you to please make member functions const whenever possible. But constant doesn’t always mean […]

  2. A Summary of “const”, Part One « C++ on a Friday Says:

    […] the last two weeks, I have mentioned const a couple of […]

  3. Disempower Every Variable « C++ on a Friday Says:

    […] have blogged about const a few times before. It is almost always a good idea to make everything that […]

  4. Shafqat Says:

    Thanks for the nice post. I use to think using const was a hassle but this made me realise why it is useful.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: