Chapter 3.2

Const Object and Const Member Function

AmazonAssume Student is a class that takes the student’s name as an argument in its constructor and getName() returns a string which is the name of the student. Let’s see how we can promise the compiler that the object will not be modified. Consider the following code snippet:

const Student saint = Student(“Maolin Yeh”);
saint.getName();

The object, saint, is declared to be const, meaning that its data members are not supposed to be altered in any way. However, the member function, getName(), needs to guarantee that it won’t modify the invoking object.

The way to achieve it is to add keyword const after the function parentheses. Here is what the getName() declaration inside Student should look like: