Tuesday, September 21, 2010

C++ Tidbits: Ampersands (&) in a Parameter of a Function

Most of the time I see these function signatures:

       int DoSomeComputation (int *x);

But I also encounter these:

       int DoSomeComputation (int &x);   //ampersand instead of an asterisk

So, what are they for/ what’s the difference?

When you use an ampersand "&" in a parameter of a function,
you are still passing a pointer (a reference).
Therefore any changes made, will be reflect to the source object.

HOWEVER, you still use the dot "." notation instead of the arrow "->" notation when accessing the members of the object (of a class or struct).

     myInfo.Name;  //instead of myInfo->Name;

this "&" option was created (by c++ makers, or whatever you call them)
because there are a lot of people who get confused when to use
the "." and the "->" notations.
------>that includes me. hehe ;)

0 comments:

Post a Comment