D
D
Denis2021-11-18 14:09:29
C++ / C#
Denis, 2021-11-18 14:09:29

C++ Operator and its overload?

DATE & operator ++()
    {
      DATE Copy(*this);
      day++;
      month++;
      year = year + 10;
      return *this;
    }

This is a code snippet, DATE is a class, day,month,yar are integer variables.
My question is, Why is a link being used here? Why pass the *this pointer as a parameter? And in general, how much do you need to overload all these operators, and is it used at all? DATE& operator ++()

DATE Copy(*this);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-18
@NeYmen

Well, that's how it's done in C++. The prefix increment operator (++i) has this signature - it returns a reference to the modified object. If you want your class Dateto be able to do ++date, then you need to redefine such an operator. This allows you to write more readable and shorter code. Instead date.IncremeantAndReturn(), you can use the idiomatic ++date, or even something like while (++date < deadline). It is not necessary to do this, but sometimes it is very convenient and useful.
The operator must return the modified value, which is why *this is returned after it has been incremented;
Not used in this code Сopy. It's not needed here at all. the copy will be needed for the postfix increment (i++), which must return an unchanged object.
Broadcast*thisto the Copy constructor is to call the copy constructor to suddenly create a copy of the current object. Think about how you can copy the current object? It is necessary to assign the current object to the new object, or pass the current object to the constructor. But how to pass the current object? You have a pointer to it this. By dereferencing this pointer (*this) you can just pass the current object to the right place.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question