There seems to be many relavent questions talking about pointer vs. reference, but I couldn't find what I want to know. Basically, an object is passed in by a reference:
funcA(MyObject &objRef) { ... }
Within the function, can I get a pointer to that object instead of the reference? If I treat the reference objRef
as an alias to the MyObject
, would &objRef
actually give me a pointer to the MyObject? It doesn't seem likely. I am confused.
Edit: Upon closer examination, objRef
does give me back the pointer to object that I need - Most of you gave me correct info/answer, many thanks. I went along the answer that seems to be most illustrative in this case.
A pointer is an object itself. It can be assigned or copied to pass a reference to a pointer as a function parameter.
Pointers vs References in C++ C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references.
A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.
Yes, applying the address-of operator to the reference is the same as taking the address of the original object.
#include <iostream> struct foo {}; void bar( const foo& obj ) { std::cout << &obj << std::endl; } int main() { foo obj; std::cout << &obj << std::endl; bar( obj ); return 0; }
Result:
0x22ff1f 0x22ff1f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With