Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is returning a constructor allowed in operator overloading?

Why is returning a constructor allowed in operator overloading?

Here is an example:

Complex Complex::operator*( const Complex &operand2 ) const
{
    double Real = (real * operand2.real)-(imaginary * operand2.imaginary);
    double Imaginary = ( real * operand2.imaginary)+(imaginary * operand2.real);

    return Complex ( Real, Imaginary );
}

It seems to be returning a constructor for the object and not the object itself? What is it returning there?

This seems to make more sense:

Complex Complex::operator*( const Complex &operand2 ) const
{
    double Real = (real * operand2.real)-(imaginary * operand2.imaginary);
    double Imaginary = ( real * operand2.imaginary)+(imaginary * operand2.real);

    Complex somenumber ( Real, Imaginary );

    return somenumber;
}
like image 845
Overtaker Avatar asked Sep 01 '14 23:09

Overtaker


People also ask

What should an overloaded operator return?

Operator Overloading is the method by which we can change the function of some specific operators to do some different task. In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded.

Which of the following is true about operator overloading?

9. Which is the correct statement about operator overloading? Explanation: Both arithmetic and non-arithmetic operators can be overloaded. The precedence and associativity of operators remains the same after and before operator overloading.

Why do we need to pass and return a reference of the stream object when we over load << and >> operators?

If your overloaded stream insertion operator function doesn't return a reference to the ostream object passed in as the first argument, the last step would not work correctly - you'd get a syntax error on the statement instead since the left operand for the next call to the operator function would be the wrong data ...


1 Answers

In C++ the syntax: Typename ( arguments ) means to create an unnamed object (aka. a temporary object) of type Typename 1. The arguments are passed to the constructor of that object (or used as initializers for primitive types).

It is very similar in meaning to your second example:

Complex somenumber( Real, Imaginary);
return somenumber;

the only difference being that the object has a name.

There are some minor differences between the two versions relating to copying or moving the object back to the calling function. More info here

1 Except when it's part of a function declaration

like image 123
M.M Avatar answered Sep 28 '22 15:09

M.M