#include <cstdlib>
#include <iostream>
usingnamespace std;
class MyInt
{
public:
MyInt(int n):val(n){}
~MyInt(){}
//set() is not guaranteed not to change the calling object
//thus a const object can't call set()
void set(int n) {val=n;}
//get() is guaranteed not to change the calling object
//thus it can be called from both const and non-const objects
int get() const {return val;}
private:
int val;
};
int main()
{
MyInt my_int(10);
const MyInt my_const_int(20);
cout << "my_int: " << my_int.get() << endl;
cout << "my_const_int: " << my_const_int.get() << endl;
my_int.set(5);
cout << "my_int: " << my_int.get() << endl;
//removing "//" from the next line will result in a compilation error
//my_const_int.set(5);
cout << "my_const_int: " << my_const_int.get() << endl;
system("pause");
return 0;
}
Constant methods are methods that logically do not alter the state of the object. In the simple case, the method "promises" not to modify any of the members.
Another common example for this is: if you dereference a const_iterator to an object, you can only call constant methods. If you have a [regular] iterator to an object, you can call any methods.