Parameter passing in C++: of the three common ways (by value, by reference, by pointer), which two allow a function to modify the caller’s original argument?
Computer Science
Object Oriented Programming Using C++
Difficulty: Easy
Choose an option
-
Areference, pointer
-
Barray, location
-
Carray, pointer
-
DNone of the above
-
Evalue, pointer
Answer
Correct Answer: reference, pointer
Explanation
Introduction / Context:How arguments are passed to functions determines whether the callee can change the caller's variables. In C++, three idioms are prevalent: pass by value, pass by reference, and pass by pointer. Understanding their effects on mutability and performance is fundamental to API design and safe coding practices.
Given Data / Assumptions:
- Language: C++ with references and pointers.
- Goal: identify which methods allow modification of the original object/variable.
- Arrays in parameter lists decay to pointers, but syntactic sugar does not change the underlying semantics.
Concept / Approach:
- By value: a copy is passed; changes affect only the local copy.
- By reference: an alias is passed; changes affect the caller's variable.
- By pointer: an address is passed; dereferencing and writing changes the caller's object.
Step-by-Step Explanation:
Evaluate each method: value (no external change), reference (allows change), pointer (allows change).Identify the two that enable modification: reference and pointer.Confirm that passing arrays typically passes a pointer to the first element, but semantics depend on how the callee uses it.Verification / Alternative check:
Example: void inc(int& x){++x;} and void incp(int* p){++*p;} both change the caller's variable when invoked correctly.Why Other Options Are Wrong:
- array, location / array, pointer: Not the canonical categories; 'location' is not a C++ passing method, and 'array' is not distinct from pointer semantics in parameters.
- None of the above: Incorrect because reference and pointer do allow modification.
- value, pointer: Passing by value does not modify the caller's original.
Common Pitfalls:
- Confusing const references/pointers (which prevent modification) with non-const ones.
- Dangling pointers/references when returning or storing addresses of local variables.
Final Answer:
reference, pointer