Wow... seems I stirred up a lively conversation on the topic.
Just to cite an example that is parallel to the original question:
1 2 3 4 5
|
// A stripped down example
class MyString {
public:
MyString operator+( const MyString& rhs );
};
|
Assume we have the above code. operator+ simply concatenates two strings. So
the intent is: MyString ("Hello" ) + MyString( "World" ) = MyString( "HelloWorld" ).
Now, the following code works fine:
1 2 3 4
|
// Assuming the appropriate constructors are implemented of course
MyString s1( "Hello" );
MyString s2( "World" );
MyString s3 = s1 + s2;
|
But the following code does not compile:
1 2 3 4
|
void Func( const MyString& s1, const MyString& s2 )
{
MyString s3 = s1 + s2;
}
|
Why? Because the compiler wants to call operator+ on object s1 with object s2 as parameter. But object s1 is const, and operator+ is not a const function, therefore the compiler cannot call it. (Note: if you change s1 to a non-const reference or pass-by-value, the code compiles fine.)
Clearly, however, operator+ would modify neither s1 nor s2, just the same as
1 2 3
|
int a = 5;
int b = 4;
int x = a + b;
|
does not modify a or b in order to perform the addition.
Moral to the story: Any time a member function of a class does not modify any of its data members, the member function should be declared const.