Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing pointers to function that takes a reference?

In C++, when you have a function that takes a reference to an object, how can you pass an object pointer to it?

As so:

Myobject * obj = new Myobject();

somefunc(obj);  //-> Does not work?? Illegal cast??

somefunc(Myobject& b)
{
 // Do something
}
like image 867
Tony The Lion Avatar asked Jul 23 '10 08:07

Tony The Lion


People also ask

Can you pass a pointer to a function that takes a reference?

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

Are pointers passed by reference or value?

Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to the old object.

Can you reference a pointer?

References to pointers can be declared in much the same way as references to objects. A reference to a pointer is a modifiable value that's used like a normal pointer.

How many ways can you pass pointer to a function call?

There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.


1 Answers

Just dereference the pointer, resulting in the lvalue:

somefun(*obj);
like image 161
GManNickG Avatar answered Sep 21 '22 14:09

GManNickG