Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ multiple operator overloads for the same operator
    text
    copied!<p>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:</p> <pre><code>class MyClass{ ... inline const MyClass operator+(const MyClass &amp;addend) const { cout&lt;&lt;"Adding MyClass+MyClass"&lt;&lt;endl; ...//Code for adding MyClass with MyClass } inline const MyClass operator+(const int &amp;addend) const { cout&lt;&lt;"Adding MyClass+int"&lt;&lt;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*/ </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload