-1

I have a function with 3 const's in it:

const std::string at(const unsigned int index) const;

To my understanding, the parameter (const unsigned int index ) means that index will not be changed. What about the other two const's? Why are they there?

Nik Bougalis
  • 10,382
  • 1
  • 20
  • 37
Sargis Plus Plus
  • 45
  • 1
  • 2
  • 11

3 Answers3

1

The first const says that the return type is const, the second const says the parameter is const, and the third const says that the function is a const function...

This question is actually a duplicate... follow this link

C++ Const Usage Explanation

Community
  • 1
  • 1
Josh Engelsma
  • 2,616
  • 13
  • 17
  • The const on the end of a member function does *not* mean the function is read only (is there even such a thing as a non-read-only function?). It means that the instance object for which the function is called is const. – Benjamin Lindley Dec 07 '13 at 06:08
1

The const keywoard in C++ indicates that a particular object or variable is not modifiable. It can be used in various contexts:

Const variables

Declaring a variable as const inside of a function indicates that the variable will not be modified inside the function.

Const member functions

Declaring a member function as const, which is done by appending const to the end of the function prototype, indicates that the function is a "read-only" function that does not modify the object for which it is called.


The rule for const viability is that const-ness can be applied to a non-const variable or member function, but once applied it cannot be removed.

Ryan Atallah
  • 2,867
  • 23
  • 34
0

const std::string at(const unsigned int index) const; in this example, the first const from left side is a constant for return type, which means whatever value it will return that can be saved in a const variable only (even type casting is possible which will change the property of data). second const as you said it is correct. third const says that the function is constant function. that means inside that function you are not modifying any variables which will change the state of objects. if you are modifying any class or global variable inside const function then compiler will throw error.

rajenpandit
  • 1,197
  • 1
  • 11
  • 19