CodeGuy
CodeGuy

Reputation: 28907

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&

Upvotes: 2

Views: 125

Answers (3)

kotlomoy
kotlomoy

Reputation: 1430

This way

myObjectClass myObj;
ClassName::Read(myObj);

You don't have to use pointers and dynamic allocation everywhere. C++ is not Java.

Upvotes: 0

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

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;

Upvotes: 5

James M
James M

Reputation: 16718

Like this:

ClassName::Read(*myObj);

Upvotes: 9

Related Questions