Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ references, addresses, pointers

I see a function definition that looks like this

ClassName::Read(myObjectClass &temp)

I'm trying to call it like this:

myObjectClass *myObj;
ClassName::Read(&myObj);

but that is incorrect. What is the proper way to call it? It needs to be of type myObjectClass&

like image 472
CodeGuy Avatar asked Aug 21 '26 13:08

CodeGuy


2 Answers

Like this:

ClassName::Read(*myObj);
like image 171
James McLaughlin Avatar answered Aug 23 '26 02:08

James McLaughlin


As James correctly points out, the correct syntax is *myObj. The point is that &myObj gives you the address of myObj, which has a type of myObjectClass**. You want instead to dereference myObj to get at the instance of myObjectClass to which it points, hence you use *.

Incidentally, as it stands at the moment, using *myObj would cause undefined behaviour, since myObj itself has not been initialised. If you don't need to dynamically allocate a myObjectClass, you might be better off just doing this:

myObjectClass myObj;
ClassName::Read(myObj);

If dynamic allocation is a must, then you can do e.g.

myObjectClass *myObj = new myObjectClass;
ClassName::Read(*myObj);
//...
delete myObj;
like image 38
Stuart Golodetz Avatar answered Aug 23 '26 04:08

Stuart Golodetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!