Tuesday, 27 September 2016

Is there any advantage of using references instead of pointers in c++?











For example, I have two functions that do the same thing:



int func(int &a)
{
return a+1;

}


and



int func2(int *a)
{
return *a+1;
}



What is the advantage of using func over func2 when calling any one of these functions?


Answer




  • A reference cannot be assigned null directly, but a pointer can be.

  • A reference cannot be reassigned to point to something else, but a pointer can be.



Both these can be advantages or disadvantages, depending on the situation.


No comments:

Post a Comment