[Solved] Why do we need to put const at the begining of the function GetMax? [closed]


I am going to put forth a few points about const so that it is clear when and what can you use as required:

Case 1: GetMax(const Type value1)

Here value1 is a local copy, I can think of a couple of points

I can think of a few reasons:

1) When someone reads the code and see const Type value1, they know that value1 should not be modified in the body of the function.

2) The compiler will tell you when you try to modify value1 in the body of the function. Therefore, adding const can prevent mistakes.

3) However, there is another difference in C++11. A constant object cannot be moved from, as a move operation modifies the object. Therefore, you can only make a copy of value1 in the function body and cannot move from it.

4) Also, if this is a class type, you cannot call non-const members functions on a const object.

Case 2: GetMax(const Type& value1)

We don’t know how value1 is used outside the function, so we want to protect it from being modified.

Case 3: const Type& GetMax()

Talking about the const before the function, means it will return a const reference to Type (here GetMax)

Take this example:

Class xyz;
Type& t = xyz.GetMax()           //This is INCORRECT
const Type& tc = xyz.GetMax()    //This is OKAY!

So, to sum up, you do not “need to use” const unless you have such requirements as mentioned above, although it might be good practice to do so in a few situations.

solved Why do we need to put const at the begining of the function GetMax? [closed]