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;
}
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.
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.
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With