C++ Difference between const positioning

c++, constants

Solution

`const int MyClass::showName(string id)` returns a `const int` object. So the calling code can not change the returned int. If the calling code is like `const int a = m.showName("id"); a = 10;` then it will be marked as a compiler error. However, as noted by @David Heffernan below, since the integer is returned by copy the calling code is not obliged to use `const int`. It can very well declare `int` as the return type and modify it. Since the object is returned by copy, it doesn't make much sense to declare the return type as `const int`.

`int MyClass::showName(string id) const` tells that the method `showName` is a `const` member function. A const member function is the one which does not modify any member variables of the class (unless they are marked as `mutable`). So if you have member variable `int m_a` in class `MyClass` and if you try to do `m_a = 10;` inside `showName` you will get a compiler error.

Third is the combination of the above two cases.

Problem

I'm struggling to get my head around the differences between the various places you can put 'const' on a function declaration in c++. What is the difference between const at the beginning: ``` const int MyClass::showName(string id){ ... } ``` And const at the end like: ``` int MyClass::showName(string id) const{ ... } ``` Also, what is the result of having const both at the beginning and at the end like this: ``` const int MyClass::showName(string id) const{ ... } ```

Original source

Related problems