Let’s start!

We use const keyword many times. The const keyword is often used in function signatures. The function signature is also called the function prototype where we mention the function name, its parameters and return type etc.

Case 1

The const keyword appears before a function parameter. E.g., in a chess program:

int movePiece(const Piece & currentPiece)

By writing const, we are saying that parameter must remain constant for the life of the function. If we try to change value, for example, the parameter appears on the left side of the assignment, the compiler will generate an error.

In short, we want it to not change the object whose the reference variable is given as parameter.

Use of const with reference parameters is very common.

Case 2

This is the case in which const keyword appears at the end of class member’s function signature as:

EType& findMin( ) const;

In this case, a member function can access the member variable but cannot change it. It means that we want to make the variables read only for that member function.

This type of usage often appears in functions that are supposed to read and return member variables.

Case 3

In this case, the const keyword appears at the beginning of the return type in function signature:

const EType& findMin( ) const;

In case 2, we don’t want to change the returned thing which is returned using reference.

REFERENCE: CS301 Handouts (page 209 to 212)

Categorized in:

Data Structures, Learning,

Last Update: March 30, 2024