I am reading this book called "C++ From the Ground Up".
I saw this and it makes perfect sense
// Using a reference parameter.
#include <iostream>
using namespace std;
void f(int &i);
int main()
{
int val = 1;
cout << "Old value for val: " << val << '\n';
f(val); // pass address of val to f()
cout << "New value for val: " << val << '\n';
return 0;
}
void f(int &i)
{
i = 10; // this modifies calling argument
}
This program displays the following output:
Old value for val: 1
New value for val: 10
Pay special attention to the definition of f( ), shown here:
void f(int &i)
{
i = 10; // this modifies calling argument
}
Notice the declaration of i. It is preceded by an &, which causes it to become a
reference parameter. (This declaration is also used in the function’s prototype.)
Inside the function, the following statement
i = 10;
does not cause i to be given the value 10. Instead, it causes the variable referenced by
i (in this case, val) to be assigned the value 10. Notice that this statement does not
use the * pointer operator. When you use a reference parameter, the C++ compiler
automatically knows that it is an address (i.e., a pointer) and de-references it for you.
In fact, using the * would be an error.
I understand that above program completely but then i see this other program about "Using a copy constructor to construct a parameter" and it just confuses the hell out of me.
Here is a section of the code
1 myclass::myclass(const myclass &obj)
2 {
3 p = new int;
4 *p = *obj.p; // copy value
5 cout << "Copy constructor called.\n";
6 }
Why is the * operator used in obj in line 4? Shouldn't that be an error? I am so confused. I am just thinking shouldn't it be automatically derefenced for you?