tags:

views:

99

answers:

3

Hi, I am trying to overload the = operator on a simple C++ class called Set that contains a dynamic array of ints. For the = operator, I first want to check for self assignment, so I wanted to compare 2 pointers to make see if they have the same memory address. Here's the code:

Set& Set::operator=(const Set& setEqual)
{
//first check for self assignment
if(setEqual == this*)
    cout << "this is self assignment";
}

The error spat out is error: expected primary-expression before ')' token

I believe I'm having a misunderstanding of pointers again, so if anyone could point (ha!) me in the right direction, I'd appreciate it.

+6  A: 

The error is becuase this* is not valid - * is either infix (in multiplication) or prefix (in dereferencing pointers).

You probably want &setEqual == this - that is assigning from an object at the same memory address or setEqual==*this - comparing equality using whatever operator== you have defined

tobyodavies
Alf P. Steinbach
I didn't even read what he was comparing, i just saw the syntax error and then gave the two possible (syntactically) correct ways of comparing equality. regardless, i feel its better to be complete - maybe he does want them compared as equal if both sets contain the name ethel, he didn't say!
tobyodavies
Hey thanks, that worked out. I'm still iffy on pointer symantics. That's a good explanation on where I should put the * and why.
Ross Hettel
+4  A: 

If you want to compare the address of the thing pointed too you really want this:

Set& Set::operator=(const Set& setEqual)
{
//first check for self assignment
if(&setEqual == this)
    cout << "this is self assignment";
}

Using (setEqual==*this) as sugested by some of the solutions compares if the objects are equal under operator==.

Michael Anderson
+4  A: 

To detect self-assignment you need

if(&setEqual == this)

you should never use

if(setEqual == *this)

for detecting self-assignment as the latter statement will invoke comparison of the objects, which might be overloaded in the way you don't expect and is likely slower as well.

sharptooth
Thanks, that helps. I am overloading the ++ operator in this class too, so I will definitely do it the first way.
Ross Hettel