Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a pointer from a reference?

Tags:

c++

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.

like image 433
Oliver Avatar asked Feb 13 '12 16:02

Oliver


People also ask

Can a pointer be passed by reference?

A pointer is an object itself. It can be assigned or copied to pass a reference to a pointer as a function parameter.

Can we reference a pointer in C++?

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.

What does it mean to reference a pointer?

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.


1 Answers

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 
like image 173
Praetorian Avatar answered Sep 23 '22 06:09

Praetorian