Originally Posted by
mickey
const Person& operator+=(const Person& right)
[...]
person1 += person2; //person1 isn't a const;
The declaration says that operator += takes a const Person& as an argument and returns const Person &. It doesn't say that "this" object should be const.
You can pass non-const objects everywhere where const objects are allowed, because "const" means simply that you can't invoke methods that change the state of the object. It doesn't change the object in any way.
class SomeClass
{
...
int x() const { return x; }
void setX( int x ) { _x = x };
...
};
...
SomeClass obj;
const SomeClass & constRef = obj;
int x1 = obj.x(); // OK
int x2 = constRef.x(); // OK --- x() is marked as const (i.e. it doesn't change object's state)
obj.setX( 10 ); // OK
constRef.setX( 20 ); // ERROR
class SomeClass
{
...
int x() const { return x; }
void setX( int x ) { _x = x };
...
};
...
SomeClass obj;
const SomeClass & constRef = obj;
int x1 = obj.x(); // OK
int x2 = constRef.x(); // OK --- x() is marked as const (i.e. it doesn't change object's state)
obj.setX( 10 ); // OK
constRef.setX( 20 ); // ERROR
To copy to clipboard, switch view to plain text mode
setX() might change the object, so we are not allowed to call, even if constRef is essentially the same thing as obj.
Also:
int x1 = constRef.x();
obj.setX( 999 );
int x2 = constRef.x(); // != x1
int x1 = constRef.x();
obj.setX( 999 );
int x2 = constRef.x(); // != x1
To copy to clipboard, switch view to plain text mode
const doesn't say that object won't change --- it says that you can't change it.
The same applies to const objects.
Bookmarks