I am working through some examples in *Sam's Teach Yourself C++ in 21 Days (5th Ed)* and I'm trying to fully understand the use of `const` methods. My question comes from a simple String class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class String
{
...
String operator+(const String&);
};
String::String operator+(const String& rhs)
{
int totalLen = itsLen + rhs.GetLen();
String temp(totalLen);
int i,j;
for (i=0; i<itsLen; i++)
temp[i] = itsString[i];
for (j=0; j<rhs.GetLen(); j++,i++)
temp[i] = rhs[j];
temp[totalLen]='\0';
return temp;
}
And in the text it states that `operator+` cannot be a `const` function because "it changes the object it is called on." I don't understand how it "changes the object it's called on" and why I cannot make a `const` function like:
in the text it states that `operator+` cannot be a `const` function because "it changes the object it is called on."
What the author means is that, in the particular example being discussed, String::operator+() modifies the object, so the function can't be const. It doesn't mean that operator+() always modifies the object, thus it can never be const.
Your example is perfectly doable, and in fact that's how std::string behaves.
Although unless String::operator[]() doesn't have a const overload, I don't see how that function modifies the object.
in the particular example being discussed, String::operator+() modifies the object
It looks like to me it actually isn't modifying the object, even stranger it is returning a copy of a temporary object that was created locally. I totally agree with what you are saying though, it just looks like the book used a bad example or the OP didn't post exactly what was in the book. If it were something like this...
I double checked and that's how it's used. Guess it's just a bad example for me to learn on. Like Athar said, I thought `operator+` would never change the object (unlike +=).
Just to get some further clarification, the book also states that a `const` function cannot "change any of the data members within the same class." This would make sense that `operator+` cannot be a `const` because it creates (and thus changes) an object of the same class. Is this true? Or should it read "within the same object."
It should be "the same object". And by "same", I mean the one that the this pointer refers to, which in the case of operator+() is the left-hand operand.
In other words,