Const References and OutParametres

Hello everyone.I have bought U5 course from Udemy.I am in the 89th lesson.I cant understand the necessity of parametres,actually outparametres,because I cant understand the usage of parametres.Also
why we print " const float& Damage" into the parameter of void PrintDamage?Actually Would you teach the fundementals of parametres and references?

When you declare a variable, it is local to where you use it. So, when calling a function it needs to have inputs and these are your parameters. Without these, functions would have a fixed purpose.

A const float is something that can’t be altered inside the function you are calling, const short for constant and float being it’s type.

The & in terms of a parameter in a call to a function is a reference, not specifically an output but can be used as such. A const float& for example is a reference but is also an input only because you can’t alter the value.

The difference between a reference (&) and not specifying this (value type) is references pass in a reference to the original variable whereas the value type parameter is a copy and for larger inputs are inefficient.

So, an out parameter can simply be a reference without a const which means the function can alter its contents.

I hope this helps and if you need more information, look up the C++ fundamentals course.


Parameters are for a function to do something with. For a simple example you could create a square function which you give it a number and it’ll give you back the square of it.

int square(int n)
    return n * n;

int main()
    int value = square(3);

- Demo


C++ uses value (i.e. copy) semantics by default, if you wanted to create a function that swaps the values of the arguments e.g.

int val1 = 10;
int val2 = 20;

swap(val1, val2);

// val1 == 20
// val2 == 10

You couldn’t do that with a function with the signature

void swap(int lhs, int rhs);

as within the function lhs and rhs would be copies of the arguments (val1 would still be 10 in the above code).

This is where references come in, you can think of them as aliases. So if the swap function was

void swap(int& lhs, int& rhs);

lhs and rhs would be an alias of the arguments passed in. so modifications to lhs and rhs would modify what was passed in - demo

const references

Sometimes you want a reference because copying might be expensive, copying an int is cheap, for something like FString, not so much as it would need to dynamically allocate enough memory and then copy the characters, which if all you wanted to do is read the string, wasted effort.

Now imagine

const FString Name = TEXT("Dan");

If Print does exactly what it says, it would be very weird if it were to modify my variable, wouldn’t it?

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms