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.
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.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
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.
Last edited by stumon; 08-05-2003 at 10:01 AM.
The keyboard is the standard device used to cause computer errors!
As stated, it means that getsignature() will not modify the variables within the calling Person object (it is allowed to modify volatile variables).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.
Last edited by 7stud; 08-05-2003 at 12:05 PM.