Sunday, July 31, 2016

C++: what is the difference between passing a reference and passing a pointer to a function?

Both are same in the kind of functionality they provide, they allow you to modify a variable of calling function.

Pointers store variable location and need special operators to access the content. References, on the other hand, also point to the same location but with a symbolic variable ('alias' of the original symbolic variable).

When we call a function with the original variable, a new copy of the variable is created and passed to the function. The references are introduced exactly to bypass the copy stage and pass the symbolic variable directly to the function.


The reason for the existence of references is that they are slightly more user friendly than the pointers. We can have normal expressions (without '*') and yet have pointer functionality.

References are even used when we do not want pointer functionality, i.e., we do not want to to change the variable in the called function. This is done by declaring the reference variable 'const'. The advantage is to avoid copy of the large objects.  

1 comment:


  1. I have joined your rss feed and look forward to webcare
    seeking more of your great post.
    Also, I have shared your site in my social networks!

    ReplyDelete