const with Member Variables

Let’s learn about whether using const with member variables is a best practice.

We'll cover the following

Introduction

Now we will learn about using const with member variables.

Previously we didn’t separate the use of const with local and member variables. Now, let’s explore that difference.

Why const members?

We may want to communicate that const members are immutable, and that their values will not change. Others may claim that there are private members for the same purpose, and private members do not require us to expose a setter for members that we consider unofficially immutable. Therefore, they would argue, it is not necessary to declare those members as const.

But, even if we firmly believe in the single-responsibility principle (SRP) and write small classes only, someone else might edit our code later on. Someone else might even change a value that was meant to be immutable.

At first glance, this seems to be a fair reason to declare member variables as const and make them officially immutable.