Consider a class for representing rational numbers, including a function for multiplying two rationals together:
class Rational{
public:
Rational(int numerator = 0, int denominator = 1);
...
private:
int n, d;
friend const Rational operator*(const Rational& lhs, const Rational& rhs);
/* why return type is const ?
Think about wrong operation if(a*b=c)
*/
};
This version of operator* is returning its result object by value.
There would not be any cost of destructor and constructor if it returns a reference instead. But remember that a reference is just a name, a name for some existing object. Whenever you see the declaration for a reference, you should immediately ask yourself what it is another name for, because it must be another name for something.
In the case of operator*, if the function is to return a reference, it must return a reference to some Rational object that already exists.
A function can create a new object in only two ways : on the stack or on the heap. Creation on the stack is accomplished by defining a local variable.Look at the example:
const Rational& operator*(const Rational& lhs, const Rational& rhs)
{
Rational result(lhs.n*rhs.n, lhs.d*rhs.d);
return result;
}
As the result , the function returns a reference to result, but result is a local object, and local objects are destroyed when the function exists.This version of operator* does not return a reference to a Rational, it returns a reference to an ex-Rational, which we cannot find any more.
Let us consider the possibility of constructing an object on the heap and returning a reference to it. Heap-based objects come into being through the use of new, so we can write a heap-based operator* like this:
const Rational& operator*(const Rational& lhs, const Rational& rhs)
{
Rational *result = new Rational(lhs.n * rhs.n, lhs.d*rhs.d);
return *result;
}
The new question has come : who will apply delete to the object conjured up by the use of new ?