0
#include <iostream>
using namespace std;

class Dummy {
  public:
    bool isitme (Dummy& param);
};

bool Dummy::isitme (Dummy& param)
{
  if (&param == this) return true;
  else return false;
}

int main () {
  Dummy a;
  Dummy* b = &a;
  if ( b->isitme(a) )
    cout << "yes, &a is b\n";
  return 0;
}

Regarding the code above, in 'isitme' function, the if condition:

if (&param == this)

Shouldn't be:

if (param == this)

as 'this' is a pointer, and 'param' is a pointer too, so if we said:

if (&param == this)

that would be a comparison between an address of a pointer (&param) and a pointer (this), which is not what we are looking for; checking if a parameter passed to a member function is the object itself?

  • 2
    What makes you think that `param` is a pointer? [`&`](https://en.wikipedia.org/wiki/Reference_(C%2B%2B)) is not `*`. – dhke Mar 18 '17 at 12:27
  • 1
    Possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – Mike Nakis Mar 18 '17 at 12:32
  • The code can be simplified: `return &param == this;`. – Christian Hackl Mar 18 '17 at 12:48

1 Answers1

0

A reference type doesn't have the same semantics with a pointer type. Its unspecified how compilers implement references. A reference type doesn't have an address per say. When you take the address of a reference type the result will always be the address of the object it was bound to.

So the code below tests the original object's address param binded to with this;

bool Dummy::isitme (Dummy& param)
{
  if (&param == this) return true;
  else return false;
}

In the case of pointers, just test the pointers for equality.

bool Dummy::isitme (Dummy* param)
{
  if (param == this) return true;
  else return false;
}
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68