views:

389

answers:

4

I have a function which takes a reference to an object-

void move(Ball& ball);

I have another function calling 'move()' which has a pointer to ball -

void foo(Ball* ball){
 //call move()
}

How is foo() supposed to pass ball to 'move()'?

Should it be like -

move(*ball);

or

move(ball);

or

move(&ball);
+10  A: 

The first one, move(*ball).

the second one, move(ball) tries to pass the pointer and the third one, move(&ball) tries to pass a pointer to a pointer.

Fredrik Jansson
+4  A: 

With the * operator on a pointer you dereference it, thus obtaining a Ball object. Since you're actually passing your parameter to a function that accepts a Ball& (so a Ball reference) only the reference will be passed, and not the whole object. The right usage is:

move(*ball);

But I suggest you to name the variables in a way that "speaks" about their nature, so ballPtr or ball_ptr would be more appropriate and you will never forget about dereferencing it.

tunnuz
+6  A: 

move(*ball);

Here's why. You can think of a reference as basically taking a pointer to the object it is handed. Thus you want the object itself, not a pointer. If you call move(ball) you will be taking a reference (pointer) to the pointer, not the object. Instead, move(*ball) dereferences the pointer and the reference then takes the pointer of that dereferenced object.

Steve Rowe
+1  A: 

the first one is correct that is move(*ball) ball is a pointer pointing to the object , you need to dereference it, after dereferencing its the object that is pointed to by ball pointer.

Zia ur Rahman