I am trying to overload operators in C++. For the purpose, I wrote the following code:
#include <iostream>
using namespace std;
class Box
{
public:
int height;
int width;
int length;
public:
Box operator+(const Box& b)
{
this->length = this->length + b.length;
this->width = this->width + b.width;
this->height = this->height + b.height;
return *this;
}
};
int main()
{
Box b1,b2;
b1.length = 5;
b1.width = 5;
b1.height = 5;
cout << "Length is : " << b1.length;
cout << "width is : " << b1.width;
cout << "height is : " << b1.height;
b2.length = 5;
b2.width = 5;
b2.height = 5;
b1 = b1 + b2 ;
cout << "Length is : " << b1.length;
cout << "width is : " << b1.width;
cout << "height is : " << b1.height;
cout << "Hello from first c++";
return 0;
}
The main part is:
Box operator+(const Box& b)
{
this->length = this->length + b.length;
this->width = this->width + b.width;
this->height = this->height + b.height;
return *this;
}
I can't understand:
this->length = this->length + b.length;
return *this;
this.length is not working here.
why should I return *this
? Is return this
is not enough here?