0

So I have a class and I am trying to increment the member x by 1. I've looked through some stuff online but I still can't understand some so I decided to ask some questions.

Questions:

  1. Am I doing my definition and implementations correctly?
  2. Why exactly do I need to create a "temp" and return it?
  3. Is the return needed? And what exactly is happening when it's being returned?

In header file:

Ship& operator++();   // prefix
Ship operator++(int)  // postfix

In implementation file:

Ship& Ship::operator++()
{
    Ship temp;
    temp.i = ++i;
    return temp;
}

Ship Ship::operator++(int)
{
    Ship temp;
    temp.i = i++;
    return temp;
}

In main:

// ships created
shipObj1++;
++shipObj2;

Thank you!

Amai
  • 141
  • 6
  • One of those should return a reference, the other a value. A detailed answer regarding how to do each can be found here: [What are the basics of operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). – WhozCraig Dec 03 '18 at 03:13
  • https://stackoverflow.com/a/4421719/434551 – R Sahu Dec 03 '18 at 03:14
  • @WhozCraig @R Sahu Yes, I looked at that before I made my post. I do not understand what exactly is happening when the temp is made. Why is it needed? Why can't one just increment the member itself? – Amai Dec 03 '18 at 03:18
  • @Amai How would you do it *without* a temporary? How would you deliver the value-before-modification back to the caller? You very-well can't modify it *after* the return statement. And creating a `void` postinc/dec operator, while feasible, is wrong. If you don't want traditional postinc/dec behavior, then don't implement the operator. – WhozCraig Dec 03 '18 at 03:23
  • @WhozCraig Sorry i'm just confused. I'm doing intro to C++ right now and this wasn't explained to me at all. The main reason I'm confused is, what if you have no need for a return value and just wish to increment the member of the class but not do anything else with it at the time. – Amai Dec 03 '18 at 03:26
  • You can ignore the return value but you must generate it. – stark Dec 03 '18 at 03:27
  • @Amai Then don't use (nor implement) post-increment. Use pre-increment which returns by reference (so no copies), and ignore the result. – WhozCraig Dec 03 '18 at 03:30
  • @WhozCraig Ah I was told to implement both for a homework project. It's okay, I will try to look over more stuff and see if I can undersatnd it better. > x – Amai Dec 03 '18 at 03:32
  • Implementing both just means following the guide we linked. The temporary for post-increment is needed to retain the original value. It is also the reason why post-operations can be *very* expensive and time consuming, particularly when the underlying object is expensive to copy. Anyway, best of luck. – WhozCraig Dec 03 '18 at 03:38

0 Answers0