Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiple operator overloads for the same operator

I know I can answer this question easily for myself by generatin the code and see if it compiles. But since I couldn't find a similar question, I thought it's knowledge worth sharing. Say I am overloading the + operator for MyClass. Can I overload it multiple times. Different overload for different types. Like this:

class MyClass{
...
inline const MyClass operator+(const MyClass &addend) const {
    cout<<"Adding MyClass+MyClass"<<endl;
    ...//Code for adding MyClass with MyClass
}
inline const MyClass operator+(const int &addend) const {
    cout<<"Adding MyClass+int"<<endl;
    ...//Code for adding MyClass with int
}
...
};
int main(){
    MyClass c1;
    MyClass c2;
    MyClass c3 = c1 + c2; 
    MyClass c4 = c1 + 5;
}
/*Output should be:
  Adding MyClass+MyClass
  Adding MyClass+in*/

The reason I want to do this is that I am building a class that I want to be as optimized as possible. Performance is the biggest concern for me here. So casting and using switch case inside the operator + overloaded function is not an option. I f you'll notice, I made both the overloads inline. Let's assume for a second that the compiler indeed inlines my overloads, then it is predetermined at compile time which code will run, and I save the call to a function (by inlining) + a complicated switch case scenario (in reality, there will be 5+ overloads for + operator), but am still able to write easily read code using basic arithmetic operators. So, will I get the desired behavior?

like image 631
eladidan Avatar asked Jun 26 '10 11:06

eladidan


1 Answers

Yes.


These operator functions are just ordinary functions with the special names operator@. There's no restriction that they cannot be overloaded. In fact, the << operator used by iostream is an operator with multiple overloads.

like image 80
kennytm Avatar answered Oct 07 '22 03:10

kennytm