Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why myClassObj++++ doesn't incur a compile error : '++' needs l-value just as buildin type do?

Why myint++++ compiles fine with VS2008 compiler and gcc 3.42 compiler ?? I was expecting compiler say need lvalue, example see below.

struct MyInt
{
    MyInt(int i):m_i(i){}

    MyInt& operator++() //return reference,  return a lvalue
    {
        m_i += 1;
        return *this;
    }

    //operator++ need it's operand to be a modifiable lvalue
    MyInt operator++(int)//return a copy,  return a rvalue
    {
        MyInt tem(*this);
        ++(*this);
        return tem;
    }

    int     m_i;
};

int main()
{
    //control: the buildin type int
    int i(0);
    ++++i;  //compile ok
    //i++++; //compile error :'++' needs l-value, this is expected

    //compare 
    MyInt  myint(1);
    ++++myint;//compile ok
    myint++++;//expecting compiler say need lvalue , but compiled fine !? why ??
}
like image 905
RoundPi Avatar asked Jul 14 '11 10:07

RoundPi


2 Answers

No, overloaded operators are not operators - they're functions. So GCC is correct to accept that.

myobj++++; is equivalent to myobj.operator++(0).operator++(0); Caling a member function (including overloaded operator) on a temprorary object of class type is allowed.

like image 63
Armen Tsirunyan Avatar answered Sep 19 '22 22:09

Armen Tsirunyan


Because for user-defined types, operator overloads are literally just function calls, and so obey the semantics of function calls.

like image 3
Oliver Charlesworth Avatar answered Sep 19 '22 22:09

Oliver Charlesworth