Search code examples
c++ns2operand

what does it mean when a function is used as left operand in C++


I'm working with NS2 that is in C++ language. I see the following code that I cannot understand it !!!!

ch->size() += IP_HDR_LEN;

thanks for your help...


Solution

  • The method ch->size() returns reference (lvalue) to something which is used in an expression.

    For example:

    class A{
     int x;
     public:
      int& getX(){ return x;}
    };
    

    then it can be used as

    A* a= new A;
    a->getX() +=5; // which is equivalent to x+=5 or x=x+5, since getX returns reference to 'x', it can be used as LHS of an expression
    

    So for your question:

    what does it mean when a function is used as left operand in C++

    Here the return value is used as left operand, not the function. The return type is a reference to something, which represents lvalue, and can be used as LHS.

    Edit

    As pointed out by @dlf, size() can return an object (by reference or by value) of any class which overloads operator +=. If returned by reference, then it is same as the above example ( just int x becomes MyClass x, int& getX() becomes MyClass& getX() ). If returned by value, although one can, but of no use or lead to bad design ( if MyClasss operator += changes some global state).