Hello all,
I have a doubt concerning to overloaded operators.
Does the compiler create new temporary object to the elements involved on the overloaded operation?
E.g. Operator + overloaded.
a = b + c;
Does the compiler creat temporary object for b and c?
See the following code and the print outs. When the + operator is called, 3 new objects are destroyed and I cant see the construction message.
I guess the default copy constructor is called by the compiler, but I am not sure.
Does any one knows the answer for this question???
Thank you,
Helbert
// Class1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Rectangle{
int x, y;
public:
Rectangle(int x, int y);
Rectangle(){cout << "Created: " << this << endl;};
void set_values(int x, int y);
int getX() {return x;};
int getY() {return y;};
int area() {return (x*y); }
Rectangle operator +(Rectangle);
~Rectangle();
};
Rectangle::Rectangle(int x, int y){
this->x = x;
this->y = y;
cout << "Created: " << this << endl;
}
Rectangle::~Rectangle(){
cout << "Retangle has been destroyed " << this << endl;
}
Rectangle Rectangle::operator +(Rectangle add){
Rectangle tmp;
tmp.set_values(add.getX(), add.getY());
return tmp;
}
void Rectangle::set_values(int x, int y){
this->x = x;
this->y = y;
}
int main(){
Rectangle rect(2,3);
Rectangle rectb(1,2);
Rectangle rectc;
cout << "AREA: " << rect.area() << endl;
cout << "AREA: " << rectb.area() << endl;
rectc = rect + rectb;
cout << "AREA: " << rectc.area() << endl;
return 0;
}