Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Difference between const positioning

Tags:

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{ ... } 
like image 827
user1055650 Avatar asked May 23 '12 09:05

user1055650


2 Answers

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.

like image 140
Naveen Avatar answered Sep 30 '22 02:09

Naveen


  1. The const attached to the return value applies to the return value. Since the return value is copied it's a pointless declaration and it makes no difference whether or not you include it.
  2. The const after the parameter list means that the function does not modify any state of the object that is not marked as mutable. This is a const member function and if you have a const object the compiler will not allow you to call non-const member functions on a const object.

There is no interaction between these two uses of const - they are completely independent constructs

like image 27
David Heffernan Avatar answered Sep 30 '22 01:09

David Heffernan