C++ General: What are the different methods to pass parameters to functions?

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

C++ General: What are the different methods to pass parameters to functions?

Q: How are parameters passed to functions?

A: In C++ there are two ways: by value and by reference. Passing by value means that a copy of the object is made on the calleeís stack and altering the object means altering a local copy so the callerís object is unchanged when the function returns. Passing by reference means that the address of the object is send (a reference holds an address but behaves like an object) so that the callee can directly alter the original object.

Q: What about passing by pointer?

A: There is no such thing; it is a misconception. A pointer is a memory address. You can pass a pointer to a function, but the pointer is passed by value. You can distinguish between the two this way: if the parameter has a trailing & then it is passed by reference, otherwise by value.

Q: May I see some examples?

A: Yes. I was about to show you some.

In this first example an integer is passed by value to function foo(), which increments it. Because a copy is made the variable in main remains unchanged and the programís output is 0 1 0.

Because passing by value requires a copy to be made, you can pass objects by value only if the type (class or struct) they instantiate provides a copy constructor, because that is the only way an object of type T can be constructor from another object of type T.

In this second example an integer is passed to foo() by reference, which means that altering it will directly affect the object in main and the output is 0 1 1.

On the other hand you can pass a pointer (address) to an integer to foo(). The pointer is passed by value (which means that if you change the pointer in foo() it wonít affect the address of the object in main) but having the address of the variable in main we can directly change it. The output is the same as in the second example, i.e. 0 1 1.

wonít work because, as I explained above, the pointer is sent by value, a copy is made and when returning to main, the pointer will hold the same address as before the call to foo (in this case NULL). To achieve what you want you must pass the pointer (the buffer start address) by reference.

* The Perfect Platform for Game Developers: Android
Developing rich, high performance Android games from the ground up is a daunting task. Intel has provided Android developers with a number of tools that can be leveraged by Android game developers.

* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.