Search code examples
javac++programming-languageslanguage-design

Operator overloading


From language design point of view , What type of practice is supporting operator overloading?

What are the pros & cons (if any) ?


Solution

  • EDIT: it has been mentioned that std::complex is a much better example than std::string for "good use" of operator overloading, so I am including an example of that as well:

    std::complex<double> c;
    c = 10.0;
    c += 2.0;
    c = std::complex<double>(10.0, 1.0);
    c = c + 10.0;
    

    Aside from the constructor syntax, it looks and acts just like any other built in type.


    The primary pro is that you can create new types which act like the built in types. A good example of this is std::string (see above for a better example) in c++. Which is implemented in the library and is not a basic type. Yet you can write things like:

    std::string s = "hello"
    s += " world";
    if(s == "hello world") {
        //....
    }
    

    The downside is that it is easy to abuse. Poor choices in operator overloading can lead to accidentally inefficient or unclear code. Imagine if std::list had an operator[]. You may be tempted to write:

    for(int i = 0; i < l.size(); ++i) {
        l[i] += 10;
    }
    

    that's an O(n^2) algorithm! Ouch. Fortunately, std::list does not have operator[] since it is assumed to be an efficient operation.