Re: Why "const rect& rhs" is used here?
"Jacky Luk" <jl@knight.com> wrote:
"Jacky Luk" <jl@knight.com> wrote:
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
I'm not sure about this but I am in doubt why when const means immutable,
but rhs is passed by reference which is mutable, they are contradicting,
aren't they?
After thinking about this some more, I thought I would point out the
difference between these two declarations:
bool operator < ( rect rhs ) const
bool operator < ( const rect & rhs ) const
Both of these are called in the same way, and in both cases the calling
procedure can know that the structure it is passing in will not be
modified.
In the first case, the compiler has to make a completely new copy of the
"rect" structure, and pass that copy to the function. The function can
modify it, but the modifications go away when the procedure returns
In the second case, the compiler merely passes the address of the incoming
"rect" structure. It doesn't have to make a copy. Because it has an
address, you'd think the function could modify the original object, but the
"const" modifier casts the compiler in the role of monitoring the code to
make sure you don't Any attempts to do so are met with a compile-time
error.
In most cases, the second is preferable because it doesn't have to copy the
entire object.
--
- Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.