Re: Why "const rect& rhs" is used here?
"Jacky Luk" <jl@knight.com> wrote in message
news:uQu0kLx1GHA.1252@TK2MSFTNGP04.phx.gbl
Hi dudes,
class rect
{
friend ostream& operator<<(ostream& os, const rect& rhs);
public:
rect (int w, int h) : _w(w), _h(h)
{ _area = _w * _h; }
bool operator < (const rect& rhs) const <<<< this one
{ return _area < rhs._area; }
private:
int _w, _h, _area;
};
=========
how come (const rect& rhs) is used
as far as i can see, the rhs is not mututed inside operator < and not
neccessary to be called by reference because
rhs will never be changed.
Things are called by reference for various reasons, one of which is to avoid
having to copy the argument --- copies take time and sometimes there is no
suitable accessible copy constructor.
You make the reference const as a programming discipline to stop you
modifying it accidentally.
And how come the operator function needs to
be declared as const (on the end of the line), as far as i can see, i
also don't see why there is a need for that... Any comments?
The const at the end of the line is because it is only functions/operators
that are declared const in this manner that can be called from a const
object, e.g., if you have
const rect rc1(5,5), rc2(3,4);
then
if(rc1 < rc2)
cout << "rc1 is smaller\n";
else
cout << "rc1 is not smaller\n";
won't compile without the const.
--
John Carson