Why does the constructor allowed when operator overloading is returned?

Why does the constructor allowed when operator overloading is returned?

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 the constructor for the object is returning, and not the object itself? What is coming back 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; } 
+5
source share
1 answer

In C ++, the syntax: Typename (arguments) means creating an unnamed object (e.g., a temporary object) of type Typename 1 . Arguments are passed to the constructor of this object (or used as initializers for primitive types).

This is very similar to your second example:

 Complex somenumber( Real, Imaginary); return somenumber; 

The only difference is that the object has a name.

There are a few minor differences between the two versions related to copying or moving an object back to the calling function. More here

1 Except when part of the function declaration

+10
source

Source: https://habr.com/ru/post/1201604/


All Articles