I noticed something today. If I create three versions of an overloaded + operators to handle every combination ( object + primitive, primitive + object, object + object) everything executes as expected:
class Int
{ int data;
public:
Int (){data = 0; };
Int (int size){ data = size; };
friend int operator+(Int, Int);
friend int operator+(int, Int);
friend int operator+(Int, int);
};
int operator+(Int lInt, Int rInt)
{ cout <<"first version. ";
return rInt.data + lInt.data;
}
int operator+(int lInt, Int rInt)
{ cout <<"second version. ";
return rInt.data + lInt;
}
int operator+(Int lInt, int rInt)
{ cout <<"third version. ";
return lInt.data + rInt;
}
int main(int argc, char *argv[]) {
Int int1 = 1;
cout << int1 + int1 <<endl; // prints "first version. 2"
cout << 3 + int1 << endl; // prints "second version. 4"
cout << int1 + 3 << endl; // prints "third version. 4"
}
But if I delete the second and third versions it still works!?!
class Int
{ int data;
public:
Int (){data = 0; };
Int (int size){ data = size; };
friend int operator+(Int, Int);
};
int operator+(Int lInt, Int rInt)
{ cout <<"first version. ";
return rInt.data + lInt.data;
}
int main(int argc, char *argv[]) {
Int int1 = 1;
cout << int1 + int1 <<endl; // prints "first version. 2"
cout << 3 + int1 << endl; // prints "first version. 4"
cout << int1 + 3 << endl; // prints "first version. 4"
}
How is my overloaded + operator, which is meant to accept two objects, able to take an int and object. How is it able to take object and an int? I hope I'm not overlooking something stupidly obvious here!