Pointer vs. Reference Parameters: A Detailed Examination
Question:
Do pointer parameters (e.g., int foo(bar* p) { ... }) and reference parameters (e.g., int foo(bar& r) { ... }) behave identically in C ?
Answer:
The difference between pointers and references goes beyond their implementation details in the standard. References embody a syntactic sugar concept, essentially creating aliases for variables. This allows compilers to optimize code where pointers would otherwise add complexity.
Functional Equivalence:
Assuming no null pointer concerns, the functions foo(bar* p) and foo(bar& r) are essentially equivalent if the someInt() method is not virtual. Both functions directly access the object's member function through the parameter. If someInt() is virtual, however, the reference-based parameter function (foo(bar& r)) will invoke the correct method based on the actual object's type, while the pointer-based function (foo(bar* p)) will always invoke the base class method.
Assigning to a Reference:
The assignment bar& ref = *ptr_to_bar will not cause any slicing. The reference ref will alias the object pointed to by ptr_to_bar, allowing you to access its members directly.
Additional Differences:
The above is the detailed content of Are Pointer and Reference Parameters Functionally Identical in C ?. For more information, please follow other related articles on the PHP Chinese website!