in
int salary() const { return mySalary; }
as far as I understand const is for this pointer, but I'm not sure. Can any one tell me what is the use of const over here?
Thanks
in
int salary() const { return mySalary; }
as far as I understand const is for this pointer, but I'm not sure. Can any one tell me what is the use of const over here?
Thanks
Sounds like you've got the right idea, in C++ const on a method of an object means that the method cannot modify the object.
For example, this would not be allowed:
class Animal {
int _state = 0;
void changeState() const {
_state = 1;
}
}
It's a const
method. It means that it won't modify the member variables of the class nor will it call non-const
methods. Thus:
const foo bar;
bar.m();
is legal if m
is a const
method but otherwise wouldn't be.
When the function is marked const
it can be called on a const pointer/reference of that class. In effect it says This function does not modify the state of the class.
It means that function can be called on a const object; and inside that member function the this
pointer is const.
It's a const member function. It's a contract that the function does not change the state of the instance.
more here: http://www.fredosaurus.com/notes-cpp/oop-memberfuncs/constmemberfuncs.html