Here is an example for friend functions found on the internet:
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle(const Rectangle &r) {
width = r.width;
height = r.height;
cout << "copy\n";
}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate (const Rectangle& param)
{
Rectangle res;
res.width = param.width*2;
res.height = param.height*2;
return res;
}
int main () {
Rectangle foo;
Rectangle bar (2,3);
foo = duplicate (bar);
cout << foo.area() << '\n';
return 0;
}
Output:
24
Notice that the friend "duplicate" function creates a local variable and returns as return value to the caller. Isn't this supposed to be a local variable and is allocated on this stack? Should not it be destroyed once "duplicate" finishes execution? Is this example good?
Thanks.