Comparing 2 references in C++

S

silverburgh.meryl

Hi,

I have a function which takes 2 references of A:

void f1 (const A& a1, const A& a2) {
if (a1 == a2)
return;
// do something else
}

My question is does this line 'a1 == a2' does an address check? or it
will calls the overloaded == operator of A?

For example, if I do this:
A* anA = new A();

f1 (*anA, *anA);

// will the overloaded == operator of A gets called? or it will not
get call since *anA points to the same address, "a1 == a2" is true.

Thank you.
 
M

Mark P

Hi,

I have a function which takes 2 references of A:

void f1 (const A& a1, const A& a2) {
if (a1 == a2)
return;
// do something else
}

My question is does this line 'a1 == a2' does an address check? or it
will calls the overloaded == operator of A?

It uses operator==. If you want an address check you can compare &a1 ==
&a2.
 
A

Alf P. Steinbach

* (e-mail address removed):
I have a function which takes 2 references of A:

void f1 (const A& a1, const A& a2) {
if (a1 == a2)
return;
// do something else
}

My question is does this line 'a1 == a2' does an address check? or it
will calls the overloaded == operator of A?

The latter.

For example, if I do this:
A* anA = new A();

f1 (*anA, *anA);

// will the overloaded == operator of A gets called? or it will not
get call since *anA points to the same address, "a1 == a2" is true.

How the function is called doesn't matter.

To do an address check do &a1 == &a2, assuming operator& isn't overloaded.
 
P

Piyo

Hi,

I have a function which takes 2 references of A:

void f1 (const A& a1, const A& a2) {
if (a1 == a2)
return;
// do something else
}

My question is does this line 'a1 == a2' does an address check? or it
will calls the overloaded == operator of A?

It will call the overloaded == operator of A (if there is one)
If you want to compare addresses of the references, you can just
take its address.

if( &a1 == &a2 ) // this will compare the addresses
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top