Small question about operator overloading

A

Alex Snast

Hello

I'm wondering if it common to return a const reference to an object

const BinSearchTree& operator= (const BinSearchTree& rhs)
throw(bad_alloc);

or

BinSearchTree& operator= (const BinSearchTree& rhs)
throw(bad_alloc);

is there any standard on those

Thanks for any help.
 
W

WaterWalk

Hello

I'm wondering if it common to return a const reference to an object

const BinSearchTree& operator= (const BinSearchTree& rhs)
throw(bad_alloc);

or

BinSearchTree& operator= (const BinSearchTree& rhs)
throw(bad_alloc);

is there any standard on those

Thanks for any help.

Generally, an operator= is defined as:
obj &operator=(const obj &rhs)
{
if(this != &rhs)
{
//do assignment
}
return *this;
}

It returns *this, because this mimics operator= for built-in types.
For example:
int i = 1, j = 2, k = 3;
(i = j) = k; //this is ok

If you return const reference, the above statement will not compile.
 
A

Alex Snast

WaterWalk כתב:
Generally, an operator= is defined as:
obj &operator=(const obj &rhs)
{
if(this != &rhs)
{
//do assignment
}
return *this;
}

It returns *this, because this mimics operator= for built-in types.
For example:
int i = 1, j = 2, k = 3;
(i = j) = k; //this is ok

If you return const reference, the above statement will not compile.

Yeah i know the difference between the two i was just wondering what
to use.

Thanks for your help
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,937
Members
47,481
Latest member
ElviraDoug

Latest Threads

Top