References and de-references

http://www.cplusplus.com/doc/tutorial/classes2/

What does it mean to have a -> de-reference sign in a if statement and why is the & reference needed in the parameter for 'isitme' function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

class CDummy {
  public:
    int isitme (CDummy& param);
};

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

int main () {
  CDummy a;
  CDummy* b = &a;
  if ( b->isitme(a) )
    cout << "yes, &a is b";
  return 0;
}
Check out the section on data structures, it explains the arrow operator (under "Pointers to structures):

http://www.cplusplus.com/doc/tutorial/structures/

The fact that it is in an if statement is irrelevant.

From the above link, we can see that b->isitme(a) is equivalent to (*b).isitme(a)


why is the & reference needed in the parameter for 'isitme' function

There is an explanation of this (pass-by-reference that is) too:

http://www.cplusplus.com/doc/tutorial/functions2/

In your example, param is just a reference to the argument passed to it.

Maybe an example of references will make a little more sense:

1
2
3
int a = 10;
int b = a; //b is a copy of a
int a_ref = a;//a_ref is a reference to a 


Play with the above code snippet a little. Print the values. Print the address of the variables. An example run (the address of a at the end is just to make comparing it to that of a_ref easier):

    a: 10
    b: 10
a_ref: 10

    address of a: 0x28ff08
    address of b: 0x28ff0c
address of a_ref: 0x28ff08
 addr again of a: 0x28ff08


As we can see b is a copy of a and a_ref is a, just a different name. Thus, when we use a reference variable as a parameter for a function, the parameter is just an alias for the argument. That means that the argument passed is directly accessible within that function (under the name of the reference of course).
Topic archived. No new replies allowed.