Archived

This topic is now archived and is closed to further replies.

MENTAL

Vector += needs to return a value?

Recommended Posts

I''ve just got the book physics for game developers (a great book, dispite the lack of CD), and i was looking at the vector, matrix and quat classes it contains at the back of the book. I already have these classes implemented in my engine and they all work fine, but for some reason the +=, -=, etc operator overloads were returning *this. Look:
  
inline Vector& Vector::operator+=(Vector u)
{
    x += u.x;
    y += u.y;
    z += u.z;

    return *this;
}
  
does anyone know the point of returning *this for the += function? my version is defined as:
  
inline void CVector::operator += (CVector &V)
{
    X += V.X;
    Y += V.Y;
    Z += V.Z;
}
  
and it works perfectly. besides, I''ve heard that calculating the "this" variable is pretty costly. thanks

Share this post


Link to post
Share on other sites
Expressions like v1 = v2 = v3 rely on operator=() returning a reference to the assignment target. The same is true of operator+=().

Anytime you want 'chaining' of operators, you need to return *this;. (edit: as a reference, not a value, for correctness reasons).

e.g. Foo.SetBar( 5 ).SetQuux( 10 );

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on October 3, 2002 9:46:34 AM]

Share this post


Link to post
Share on other sites
pos += delta_time* (vel += delta_time*force );



do you know the

while(count--) {
do();
}
syntax?..

guess what..
while(count-=2 > 0) {
do();
}
can be handy as well..

"take a look around" - limp bizkit
www.google.com

Share this post


Link to post
Share on other sites
*sigh* i thought so

davepermen: i just so i know i''m on the right track, i gather that''s the same as

vel += delta_time * force;

pos += delta_time* vel;

anyway, thanks to both of you for the help (and the extra work!)

Share this post


Link to post
Share on other sites
yes thats the same..

you don''t need it if you don''t want those features, but most the time you don''t even know that u use them... so bether follow the standarts there..

"take a look around" - limp bizkit
www.google.com

Share this post


Link to post
Share on other sites