Why do we need the '&'?

bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, &FVector LookDirection) const

Why do we need the ‘&’ if it works without it?

As far as I understand;

when passing a function parameter (i.e. MyFunction(&MyParameter) ) using the ampersand (&) character, or by reference, we pass the same physical memory location to the function. This means that the function can change the value of the variable as it is outside the function (scope).

If we pass it without the ampersand, we create a copy of the variable, meaning you have to return that copy from the function after changing it if you want to have access to these changes later on (e.g. MyParameter = MyFunction(MyParameter) { return MyParameter; } ) (This last bit might be a confusing albeit very basic example).

If you want to learn more about it, there is an interesting discussion on passing by reference on SO here:

1 Like

In my opinion we use ampersand because we want to change outside the function.

Theses answer are right, if you don’t put the &, you create a copy of it, which means that all the pointers that are using this “LookDirection” value aren’t gonna have the updated value of it.

It’s also for performance. In this case, LookDirection is a small object, but let’s say you had a really big object. You wouldn’t want to copy it in memory each time you call a function. So the pointer says to the function: “Here, I give you the address where you can find the data, you can modify it directly”.

There’s a great page on Unreal on that: https://wiki.unrealengine.com/Entry_Level_Guide_to_UE4_C%2B%2B#Pointers

Don’t hesitate if you have other questions!

Privacy & Terms