CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    postfix and prefix operator overloading question

    Usually, postfix and prefix operator overloading is defined as follows,
    Code:
     class Number {
     public:
       Number& operator++ ();    // prefix ++
       Number  operator++ (int); // postfix ++
     };
    My question is that why prefix returns by value and postfix returns by reference?

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: postfix and prefix operator overloading question

    Quote Originally Posted by LarryChen
    My question is that why prefix returns by value and postfix returns by reference?
    You actually mean to ask why the prefix version returns by reference and the postfix version returns by value. We normally expect the prefix version to return the updated value, hence it would typically return *this; Therefore, there is no point in returning by value when you do not need a copy. But we normally expect the postfix version to return the previous value, hence it is sensible to return a copy of the object before the increment.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Aug 2009
    Location
    Romania->Felnac
    Posts
    48

    Re: postfix and prefix operator overloading question

    The postfix ++ does not return a reference because it will be invalid, example for build-in int operator++ :

    ++x; // returns x+1

    x++; /* create a copy let's say tmp = x; then x = x + 1; and finally return the tmp value, a tmp reference will be invalid */

    This is the reason why: ++var is more efficient then var++, no copy and no temporary variable.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured