I've made a very simple program trying to understand operator overloading in C . However as you too will see, the result of the dimention d3 is not updated even though the appropriate values are returned from the operator overloading.
#include <iostream>
using namespace std;
class dimention{
protected:
int width, height;
public:
dimention(int w = 0, int h = 0){
width = w;
height = h;
}
int getWidth(){
return width;
}
int getHeight(){
return height;
}
dimention& operator = (const dimention &d){
dimention *temp = new dimention;
temp->height = d.height;
temp->width = d.width;
return *temp;
}
dimention& operator (const dimention &d){
dimention *newDimention = new dimention;
newDimention->width = this->getWidth() d.width;
newDimention->height = this->getHeight() d.height;
return *newDimention;
}
};
int main(){
dimention *d1 = new dimention(5, 5);
dimention *d2 = new dimention(1, 1);
dimention *d3 = new dimention;
*d3 = *d1;
cout << d3->getHeight() << endl;
cout << d3->getWidth() << endl;
*d3 = *d1 *d2;
cout << d3->getHeight() << endl;
cout << d3->getWidth() << endl;
return 0;
}
Thanks for your help.
CodePudding user response:
I think you misunderstand the way methods operate on an object.
Consider the assignment operator:
dimention& operator = (const dimention &d){
dimention *temp = new dimention;
temp->height = d.height;
temp->width = d.width;
return *temp;
}
You are never editing the object itself (this
) that is being assigned to. Instead, you are creating (and leaking) a new temp
object and changing it. That object is not d3
.
A correct implementation would be:
dimention& operator = (const dimention &d){
this->height = d.height;
this->width = d.width;
return *this;
}
Same here:
dimention& operator (const dimention &d){
this->width = d.width;
this->height = d.height;
return *this;
}
Will give you the expected result.