Question about Tut 19

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
zokerus
Posts: 2
Joined: February 20th, 2017, 7:13 pm

Question about Tut 19

Post by zokerus » February 21st, 2017, 10:29 am

Hello Guys,
I have a question concerning tutorial no. 19. In this tutorial Chili introduces the Vec2 class and at the point 18:05 min he changes the constructor parameter of the poo class. I don't understand why he users a reference of the Vec2.

Code: Select all

void Init(const Vector2& pos_in, const Vector2& vel_in);
I my mind, by using a reference of this Vec2 parameter would create a invalid reference as soon as the origin is disposed, but this don't happen.

Code: Select all

poos[i].Init(Vector2(xDist( rng ),yDist( rng )),Vector2(vDist( rng ),vDist( rng )));
Can someone explain it to me??

Best regards,
zokerus

User avatar
SlevinKelevra
Posts: 80
Joined: September 9th, 2013, 12:58 am
Location: Germany

Re: Question about Tut 19

Post by SlevinKelevra » February 21st, 2017, 10:58 am

The big advantage of passing by reference is that a copy of the argument is not made. It is fast, even when used with large structs or classes. Const reference does not allow you to change the value.

In the Init function the two Vec2 (pos and vel) are copied to the poo members. The reference values are not used anymore from then on.
Carpe noctem

User avatar
chili
Site Admin
Posts: 3948
Joined: December 31st, 2011, 4:53 pm
Location: Japan
Contact:

Re: Question about Tut 19

Post by chili » February 21st, 2017, 12:27 pm

zokerus wrote:
I my mind, by using a reference of this Vec2 parameter would create a invalid reference as soon as the origin is disposed, but this don't happen.

Code: Select all

poos[i].Init(Vector2(xDist( rng ),yDist( rng )),Vector2(vDist( rng ),vDist( rng )));
Can someone explain it to me??

Best regards,
zokerus
When you initialize a variable with a reference to another variable, it copies the value of the referenced variable into the variable for initialization. The variable that is to be initialized does not transform into a reference. Also, references behave exactly like normal variables after they are initialized, so you don't have to worry about that.

The only time you would have a problem of invalid reference is if the member that is being initialized is a reference.
Chili

zokerus
Posts: 2
Joined: February 20th, 2017, 7:13 pm

Re: Question about Tut 19

Post by zokerus » February 21st, 2017, 2:39 pm

Hi Guys,
thank you for your quick response. Now I understand what you did there and I can continue with the tutorials.

Thank you and best regards,
Zokerus

Post Reply