The const keyword

The const keyword is used to show both other developers and the compiler that an object is constant and its contents cannot be changed. If you anyway try to change the contents of a const object will generate an error already at compile time. It is a good practice to add the const keyword to a parameter, a members or a method to show that the value is not going to be changed. This can both make the intent of the code more clear to the user, and can make the code faster since the compiler can make certain optimizations knowing that the object is not going to change its value.

The difference between the const keyword and the constexpr keyword is that the value of a constexpr constant must be resolved at compile time whereas the value of a const constant can be resolved at run time (or at compile time).

The const keyword can be used in the following contexts:

Const class

An object can be made constant at creation by declaring the object as const:

Any attempt to change the contents of the object christmasDay will result in a compiler error:

 

Const member functions

Adding the const keyword to a member function (added at the end of the function declaration, after the parameters) states that this method will not change the state of the object.

The const keyword after the declaration of the method getYear() shows that calling this method will not change any members of the object. This also means that we are allowed to call this method even if the object is const.

 

Const parameters

Parameters to functions can also be declared as const. There are two positions where the const keyword can be added.

 

 

 

Facebookgoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *