Microsoft Interview Question
Software Engineer in TestsWhen To Pass an Argument by Value
*
If the calling code element underlying the argument is a nonmodifiable element, declare the corresponding parameter ByVal. No code can change the value of a nonmodifiable element.
*
If the underlying element is modifiable, but you do not want the procedure to be able to change its value, declare the parameter ByVal. Only the calling code can change the value of a modifiable element passed by value.
When To Pass an Argument by Reference
*
If the procedure has a genuine need to change the underlying element in the calling code, declare the corresponding parameter ByRef.
*
If the correct execution of the code depends on the procedure changing the underlying element in the calling code, declare the parameter ByRef. If you pass it by value, or if the calling code overrides the ByRef passing mechanism by enclosing the argument in parentheses, the procedure call might produce unexpected results.
When we know that we want to leverage the run-time polymorphism features provided by the library.
When the class defines a virtual function in C++/Java and that function isn't invoked using expected reference/pointer then we see compile time binding as the object on which the function is to be invoked is available to the compiler.
I like answer number one. Just adding that when you want to guarantee no modufication, you need to pass it at as const ref. Also, if for some reason you need to change the value of the variable inside the function and don't want to be copying a complex object when passing it as a parameter to the function and then back when returning it modified. e.g. bool fillHash( Hash& myHash ) you can pass it without const.
1) When null is unacceptable.
- Nitesh April 02, 20102) When its a large\heavy object or a collection of objects and its not being modified in the function
3) In a Copy constrctor of a class.