Hi All

Can somebody clear my query that why the second operand of '+' operator is called first in the code below?
When operator '+' takes left to right.

#include <iostream>
using namespace std;

class A
{
    int i;
        public:
        A(int i=-1){cout<<"A const i = "<< i <<endl;}

        int operator+(const A &a)
        {
            cout<<"operator + "<<endl;
            return 1;
        }
};

int main()
{
        A(10) + A(18); // A(18) is constructed first !! Why??
        return 0;
}

Recommended Answers

All 3 Replies

The 'left to right' order you refer to is the operators associativity. This is nothing to do with what order the operands are evaluated in but is to do with the order multiple operators of the same preceedence are evaluated in, for example the left-to-right associativity of + and -, which have the same preceedence, means that a - b + c is evaluated as (a - b) + c and not a - (b + c) which would result in a completely different answer.

As Moschops points out the compiler is free to evaluate the 2 operands of any operator in any order it chooses with the exception of || and && which have to evaluate the left hand operand first to achieve short-circuit evaluation.

What Moschops and Banfa said. In any case, the short answer is "it is implementation dependent". This is similar to the order that arguments passed to a function are evaluated. The compiler writer is free to evaluate them right to left, or left to right. So, don't make any assumptions!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.