6

I'm experimenting with operator overloading and found something that I cannot explain:

WeekDays.h

using namespace std;
enum DAYS
{
    MON,
    TUE,
    WED,
    THU,
    FRY,
    SAT,
    SUN
};

DAYS operator+(DAYS&a,DAYS &b)
{
    printf("Binary+ called\n");
    return (DAYS)(((unsigned int)a+(unsigned int)b)%7);
}

//Increment 3
DAYS operator+(DAYS&a)
{
    printf("Unary+ called\n");
    return (DAYS)(((unsigned int)a+3)%7);
}

ostream& operator<<(ostream&o, DAYS &a)
{
    switch(a){
    case MON: o<<"MON"; break;
    case TUE: o<<"TUE"; break;
    case WED: o<<"WED"; break;
    case THU: o<<"THU"; break;
    case FRY: o<<"FRY"; break;
    case SAT: o<<"SAT"; break;
    case SUN: o<<"SUN"; break;
    }
    return o;
};

Main.cpp

#include <iostream>
#include "WeekDays.h"
using namespace std;

void main()
{
    DAYS a=MON; //=0
    DAYS b=TUE; //=1
    cout<< +a       <<endl;
    cout<< +b       <<endl;
    cout<< +(a,b)   <<endl;
    cout<< (a+b)    <<endl;
    cin.get();
}

Output is

Unary+ called
3
Unary+ called
4
Unary+ called
4
Binary+ called
1

Why is +(a,b) evaluated as unary operator +b ? I've failed to explain this.

Link to relevant thread Operator overloading . I'm Using VisualStudio 2012.

Community
  • 1
  • 1
Lorenzo Belli
  • 1,767
  • 4
  • 25
  • 46

2 Answers2

10

With (a,b) you happen to invoke the odd "comma" operator, which evaluates first a, then b, and finally returns b.

You could call your operator by spelling it out as operator+(a,b). (Here the comma is a separator for the parameters, and not the comma operator).

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • Since both unary and binary + operators have higher precedence I would expect `+()` to be evaluated first, thus interpreting the comma as separator instead of comma operator. How does the compiler decide that `+(a,b)` is unary+? – Lorenzo Belli Aug 31 '15 at 11:35
  • 1
    @LorenzoBelli parentheses changes the order of evaluation: `+(a,b)` first evaluates the content of the parentheses and then the unary `+` while +a,b first evaluates `+a` then the comma and then the b. – PaperBirdMaster Aug 31 '15 at 13:16
1

Please take a look at the link http://en.cppreference.com/w/cpp/language/operator_arithmetic

unary plus, aka +a

T::operator+() const;   
T operator+(const T &a);

addition, aka a + b

T::operator+(const T2 &b) const;    
T T operator+(const T &a, const T2 &b);

With your overloaded operator+(a,b) you should get at least this warning: warning: left operand of comma operator has no effect [-Wunused-value]

Tomas
  • 176
  • 3