Keyword “const” in C++

When declaring a member function as const, it means that the function is not allowed to modify the object on which it is called. This allows you to call the function on a const object, ensuring that the object’s state is not changed.

In the case of the getFirstName() member function in the example I provided, the function itself is not modifying the object, but it is returning a reference to a data member (firstName) of the object. In order to allow this member function to be called on a const object, the return value must also be const.

Therefore, the declaration of the getFirstName() function needs to include two const keywords:

const char* getFirstName() const { return firstName; }

The first const keyword indicates that the function is const and does not modify the object, while the second const keyword indicates that the return value is also const and cannot be used to modify the firstName data member of the object.

By declaring the member function in this way, you can ensure that the firstName data member is not modified when the getFirstName() member function is called on a const object, while still allowing the function to return a reference to the firstName data member.