Assignment operator overload returns a C++ reference

Asked

Viewed 45 times

1

I’m having doubts about the overload of C++ language operators. I could not understand why the overload of the atibuição operator returns a reference, if I give a return *this (to my understanding) it does the process of melting and returns the content not the address. Could you help me please?

1 answer

1


I could not understand why the overload of the atibuição operator returns a reference.

Not necessarily, the programmer’s choice.

if I give a Return *this (to my understanding) it makes the process of melting and returns the content not the address.

In the case if return is a reference, no, returns only the reference.

Let’s look at a simple case:

struct complex
{
   float real = 0, imaginario = 0;
   complex& operator=(float real_val);
};

complex& complex::operator=(float real_val)
{
   real = real_val;
   imaginario = 0;
   retuen *this;
}

By the simple fact that the operator returns a Voce reference you can do:

complex a, b;
a = (b = 10); //não precisa dos parenteses

Because b = 10 returns a reference to b (not a copy of the value of b), a is initialized with the value of b.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.