Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ declaring a variable when passing it into a function

I come from a world of c# were doing something like this is allowed. When I try it in c++ I get no compiler errors but I am not convinced it is actually working.

So to more experienced people are you allowed to do something like this:

Entity->SetPosition(Vector2(200, 400));

As In Vector2 is a class and the parameter for set position requires a vector? Is this allowed or do I need to pre-initialize the variable like so:

Vector2 aVector(200, 400);
Entity->SetPosition(aVector);

Thanks David

like image 866
DavidColson Avatar asked Jul 30 '26 19:07

DavidColson


1 Answers

Entity->SetPosition(Vector2(200, 400));

is fine (and preferable) if you've defined SetPosition as one of the following:

void SetPosition(Vector2 const & v); //Okay : const reference
void SetPosition(Vector2  v);        //okay : value

that is, SetPosition accepts the argument as const reference, Or simply as value.

This wouldn't work though:

void SetPosition(Vector2 & v);  //not okay : non-const reference

--

In C++11, you could just write this (provided you have implemented Vector2 to enable this behavior):

Entity->SetPosition({200, 400});

Thanks to @Simon for pointing this out.

like image 167
Nawaz Avatar answered Aug 02 '26 10:08

Nawaz



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!