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
}
A pointer is an object itself. It can be assigned or copied to pass a reference to a pointer as a function parameter.
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.
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.
There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.
Just dereference the pointer, resulting in the lvalue:
somefun(*obj);
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