I just saw a topic about Reference and Pointers and whether they are same thing or not. I think it’s time for some brief introduction for everyone.
A pointer: It holds the value of the physical address of something else. Given an int* it will hold address of an int.
A reference: It "refers" to another variable UPON INITIALIZATION. Unlike pointers, it can’t be changed to refer something else. Nor can you do Arithmetic on a reference. The syntax is also different--you no longer need to add the * Asterisk to access to original object.
But in machine level, reference is actually based on a pointer; the compiler did the job about all the dereferencing part.
Q: Then why bother to have a reference?
A: Because of the Copy constructor.
when an object is returned from a function or when an object is passed into a function as an argument, the Copy constructor is called because a copy needs to be created on the stack.
This is the syntax of it
Class_name (Class_name const &source)
now why can’t we use something like this instead?
Class_name (Class_name const source)
Because then when the source is passed into the function the copy constructor needs to be called which means you need to create source which means you need to call the copy constructor! This will become an infinite loop.
How about a pointer?
Class_name (Class_name const *source)
But then this constructor will only work on those pointers--real object won’t trigger a call to copy constructor.
This is the reason Reference is created:
(1) It doesn’t require initializing a new object--Infinite loop solved.
(2) It can be triggered by the object itself instead of a pointer.
That’s all I know about Pointers and References and PLEASE STOP ARGUING WHETHER THEY ARE SAME THING OR NOT.
I am new to C++ so if any mistakes were made please tell me. Thanks :)
Again Thank you all.