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?
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?
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;
}
}
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.
A const after function of a class, means this function would not modify any member objects of this class. Only one exception, when the member variable is marked with Mutable.
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.
It means that function can be called on a const object; and inside that member function the this
pointer is const.
It just guarantees that calling salary() doesn't change the object state. IE, it can be called with a const pointer or reference.
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