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{ ... }
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.
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.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With