Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ operator++ overloading, prefix vs postfix

  1. Dec 12, 2011 #1
    I have seen how people implement the prefix and postfix ++ overloading, which are as follow:

    Number& operator++ () // prefix ++
    {
    // Do work on this.
    return *this;
    }

    Number operator++ (int) // postfix ++
    {
    Number result(*this); // make a copy for result
    ++(*this); // Now use the prefix version to do the work
    return result; // return the copy (the old) value.
    }

    What I don't understand is:
    When you call ++m1 and m2++, how does the machine know it should call Number& operator++ () for m1 and Number operator++ (int) for m2? I look at it and think about it for a long time, but I still couldn't tell from the syntax how it is done. Did I miss something obvious?
     
  2. jcsd
  3. Dec 12, 2011 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    The prefix and postfix versions have different signatures. The (int) argument to the postfix version of operator++ is a dummy argument. It's a built-in feature of the language specification that ++m1 translates to a call to operator++(), m2++ to a call to operator++(int).
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++ operator++ overloading, prefix vs postfix
Loading...