As you may know, I have been developing a game engine using OpenGL and C++. I have tried learning as much about C++ as I could. Recently I decided to reread the Effective C++ book and apply what I have learned from the book into the engine. However, I also decided that I should also share with you what I learn. Today I read the following tip in the Effective C++ book:
Have assignment operators(=,+=,-+,*=,etc.) return a reference to *this
For example, the method below; since its an assignment, should be written as follows:
class Point{
public:
//...
//this is an assignment operator
Point& operator=(const Point& rhs){
//...
//Thus, make sure to return *this
return *this;
}
}
The same applies to any other assignment operators such as: +=,-=, *=, etc
class Point{
public:
//...
//this is another assignment operator
Point& operator+=(const Point& rhs){
//...
//So, also make sure to return *this
return *this;
}
}
This is a convention, any code that doesn't follow this rule will compile just fine. However, this convention is used by all built-in types and the standard library, so it is a good idea for you to follow it as well.