Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a pointer to a reference

Tags:

c++

I'm using a library which has a draw function which takes a reference to a circle. I wish to call this function but I have a pointer to my circle object. Can I pass this pointed to object to the draw function? If not, why not?

Thanks,

Barry

like image 714
Baz Avatar asked Jul 25 '11 15:07

Baz


People also ask

Can you assign a pointer to a reference?

You can assign pointers to "point to" addresses in memory. You can assign references to "refer to" variables or constants. You can copy the values of pointers to other pointers. You can modify the values stored in the memory pointed to or referred to by pointers and/or references, respectively.

How do I send a pointer as a reference?

Note: It is allowed to use “pointer to pointer” in both C and C++, but we can use “Reference to pointer” only in C++. If a pointer is passed to a function as a parameter and tried to be modified then the changes made to the pointer does not reflects back outside that function.

What does it mean to reference a pointer?

A reference to a pointer is a modifiable value that's used like a normal pointer.

How do you assign a pointer?

The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double ) too. Naming Convention of Pointers: Include a " p " or " ptr " as prefix or suffix, e.g., iPtr , numberPtr , pNumber , pStudent .


2 Answers

Yes you can.

You have this function

void DoSth(/*const*/Circle& c)
{
   ///
}

You have this pointer

/*const*/ Circle* p = /*...*/;

You call it like this

DoSth(*p);

I suggest that you should read a good C++ book. This is really fundamental stuff.

like image 149
Armen Tsirunyan Avatar answered Oct 07 '22 21:10

Armen Tsirunyan


As long as pointer is not destroyed while the reference is still being used it is fine.

int *p = new int;
int &r = *p;
like image 23
Tom Kerr Avatar answered Oct 07 '22 20:10

Tom Kerr