DavidColson
DavidColson

Reputation: 8597

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

Upvotes: 3

Views: 164

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

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.

Upvotes: 8

JaredPar
JaredPar

Reputation: 755161

In general yes this is just fine. In general a Set style API in C++ will take either a value or a const & to the value being set. In both of those cases it's fine to use an inline expression.

class Entity { 
public:
  void SetPosition(const Vector2& value) { ... }
  void SetPosition(Vector2 value) { ... } 
};

It isn't legal though in the case where SetPosition takes just a reference

void SetPosition(Vector2& value) { ... }

This isn't the common idiom for setters though

Upvotes: 1

Related Questions