The code below shows a class representing complex numbers. My interest is in understanding the operator+
function. As I understand Complex res
should be allocated on the frame of the function operator+
. Is it correct to return this object to the caller? By the time this function returns the frame would have been popped but res
would continue to be used by the caller. Unless there is more to this than meets the eye, like the actual return res
may actually be copying the object from current frame to the caller's frame. Another possibility can be that the code inside the operator+
function may be inlined on the call site in main? From my limited understanding of the language, functions declared within the class are by default inlined on the call site. Any help will be appreciated.
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
PORTION BELOW ADDED TO CLARIFY THE SOLUTION AFTER READING THE COMMENTS AND ANSWERS BELOW
I updated the code above with the following:
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
cout << "Address inside the function " << &res << "\n";
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
cout << "Address outside the function " << &c3 << "\n";
c3.print();
}
The output shows two different addresses on two different regions of the stack indicating copy by value during return:
Address inside the function 0x7fffbc955610
Address outside the function 0x7fffbc955650