Monday, May 24, 2010

I need help understanding between call by reference and call by value in C++?

Please, guys, I've looked around the web for extra tutorials I can't seem to be grasping this simple concept. I need to know about it for tomorrow's test... If you guys can explain in a simple way I'd be even happier... thanks..

I need help understanding between call by reference and call by value in C++?
Here's a video that explains passing arguments by reference and value:





http://xoax.net/comp/cpp/console/Lesson1...
Reply:When you call a method by reference, the callee sees the caller’s original variables passed as parameters, not copies. References to the callee’s objects are treated the same way. Thus any changes the callee makes to the caller’s variables affect the caller’s original variables.





Basically, when you call by reference - you're actually working with the original object, so modifications to that object will reflect in the original. Calling something by value effectively creates a duplicate value.
Reply:if you call by reference


void foo( Thingy%26amp; param){


param++;


}


when foo finishes, the value you passed into foo comes back altered...





when you pass by value


void foo2(Thingy param){


param++;


}


a copy of param is made and it's the copy that's modified, so after your call has finished your original calling parameter isn't altered





Thingy iAmAltered, iAmStillTheSame;


foo( iAmAltered );


foo2(iAmStillTheSameAfterwards);








the function modifies what it's been given, the first time you passed it a reference to the variable, so the variable got modified, the second time you made a copy, put the copy on the stack and the copy got modified.





if you want some bonus points in your test, you should always pass by reference, as this only ever loads 4bytes (the reference/pointer size) on to the stack where as passing by value a large instance puts as many bytes as the instance is big on the stack,


thus if you're not wanting to modify your parameter but you're passing by ref you'd make the parameter const for safety :)


foo3( const Thingy%26amp; param ){


param++;//this won't compile because it's a const...


}
Reply:In a function call, parameters are put on the stack.


Call by value - the value is put on the stack. The function can change the value internally, but the caller's copy is unchanged.


Call by reference - a pointer is put on the stack. If the function changes this value, the caller's copy is also changed.


No comments:

Post a Comment