Search code examples
c#c++operator-overloading

C++ operator overloading


In C#, the method(function) of overloading any operator must be static and public.

I see that making it static is a good thing, every object doesn't need its own version of it.

But in C++, it doesn't have to be static. Why does C# enforce this and C++ doesn't?

What are the advantages and disadvantages of both designs?


Solution

  • why C++ Doesn't enforce operator overloading to be "Static" ?
    If you make overloaded operator function static it wont have access to this. One would need access to this inside the overloaded function, as usually the function would change the state of this.

    You can make a overloaded operator function static if you don't need access to this inside that function, which essentially means you are not manipulating the state of the object on which the operator function was invoked. So it is opssible but not usual or essentially desired.

    Making an globally overloaded operator function static would limit the scope of the operator function to the same file.

    Given the both above, Compiler doesn't enforce overloaded operator functions to be static since enforcing it would provide no real advantage or convenience, rather not enforcing the same provides more convenience.

    why C# enforces operator overloading to be "Static" ?
    This explains it much better than I can.

    What are the advantages and disadvantages?
    Well, the answer to the first Question does say out when one could make a overloaded operator function static & that explains the advantage/disdvantage.