Will someone please tell me what the 'const' after the 'getsignature()' in the above code does?Code:class Person: public Sortable
{
int getsignature() const; //what is the significance the const here?
}
Thanks.
Printable View
Will someone please tell me what the 'const' after the 'getsignature()' in the above code does?Code:class Person: public Sortable
{
int getsignature() const; //what is the significance the const here?
}
Thanks.
It means that the function is not going to modify the particular instance of the object calling the function.
The const applies to the calling objects. If you have a member function that should not change the value of the calling object then you put the const. Then you will receive a error if your function changed the value of the calling object.
As stated, it means that getsignature() will not modify the variables within the calling Person object (it is allowed to modify volatile variables).Quote:
Originally posted by kes103
Will someone please tell me what the 'const' after the 'getsignature()' in the above code does?Code:class Person: public Sortable
{
int getsignature() const; //what is the significance the const here?
}
Thanks.
The keyword means the method itself is const, so it cannot modify the object it operates on. Methods can be broken into two categories: modifiers, which change the state of the object, and accessors, which merely allow an outsider to view parts of the state of the object. Modifiers cannot be const, accessors should be.
A const object can only be used to call const functions. For example:
Code:void F(const Person & p){
p.getsignature(); // this is legal because getsignature is const
}
Also, I'm sure this will trip you up at some point:
Only member functions of a class can be labeled const--not other functions.