Hacker News new | ask | show | jobs
by NaNDude 1231 days ago
i've seen you'v been recommended to learn C in another thread. in C++, the use of "references" really require to understand the concept of pointers, they'r basically the same things but not exchangeable, because references hide some aspects of pointers that make the syntax a little more shitty. in fact the syntax of references (the use of '&' in parameters) come from the syntax of pointers, it means "address of".

int incr2(int& value) { value = value + 1; return value; }

is the same as

int incr3(int* value) { (*value) = (*value) + 1; return *value; }

and they will be used diferently for the same result :

void main() {

  int a_value = 5;

  int result2 = incr2(a_value); // result2 = a_value = 6;
  int result3 = incr3(&a_value); // resulst3 = a_value = 7;
}

in the call to incr3 "&a_value" can be read : address_of "a_value".

and in the body of incr3 "*value" can be read : content of address "value".

and finnaly in the prototype "int incr3(int* value)", "int*" can be read : pointer to an int, or address of an int.

pointer/address are a fundamental concept for programming at large, the concept of "indirection".

all this may seem unrelated at first, but in your Complex problem, you can try something like :

#include <iostream>

...

Complex c2;

std::cout << &c2 /* address of c2 */ << std::endl;

and in your copy constructor :

Complex(Complex& c) {

  std::cout << &c /\* address of c \*/ << std::endl;

  ...
}

you will see that, with a reference, the addresses are the sames, but without references you will get different addresses meaning that your variables are'nt the same (in the case of function parameters/arguments they are copies of the parameters values, that's why we call this "pass by value" semantic, rather than "pass by reference" or "pass by address" or box, or indirection, or whatever having the same meaning).

hope this help.