Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator overloading called as function

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.

like image 520
Lorenzo Belli Avatar asked Aug 31 '15 11:08

Lorenzo Belli


2 Answers

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).

like image 161
Bo Persson Avatar answered Nov 18 '22 01:11

Bo Persson


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]

like image 31
Tomas Avatar answered Nov 18 '22 01:11

Tomas