0

I am a beginner and puzzled by the uses of reference. I have been studying a lot on pointer. Recently, I start working on reference. Can I summarize reference in a sentence like that "what references can do, can be done with using pointers"

As I see, pointer store an memory address, so we can go into specific address to do things but reference doesn't even take a memory, it's just a alias.

Here is pointer implement

#include <iostream>
using namespace  std;

void Increment(int* value)
{
   (*value)++;
}
int main()
{
   int a = 8;
   int* ptr_a = &a;  
   Increment(ptr_a);
   cout << a << endl;
   std::cin.get();
} 

and here is reference implement

#include <iostream>
using namespace  std;

void Increment(int& value)
{
    value++;
}
int main()
{
    int a = 8;
    int& ref_a = a;  
    Increment(ref_a);
    cout << a << endl;
    std::cin.get();
}

I get the exactly same output. As a result, can I conclude the differences as "Pointers cover all the function of references"?

Thank you

William
  • 1
  • 1
  • 1
    https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in – SzymonO Jun 17 '20 at 09:08
  • 1
    with great power comes great responsibility ;). Often what you can do more with pointers is not needed but still is potential bugs and mistakes. Sometimes less is more – 463035818_is_not_an_ai Jun 17 '20 at 09:11
  • As someone writing an interface, you (almost)always get to reasonably assume that references are non-null. (You can kind of do the same thing with pointers, but it's only easy to assert non-null pointers at runtime, which can lead to bugs in release builds) – George Jun 17 '20 at 09:14

0 Answers0