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.