From language design point of view , What type of practice is supporting operator overloading?
What are the pros & cons (if any) ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT: it has been mentioned that
std::complexis a much better example thanstd::stringfor “good use” of operator overloading, so I am including an example of that as well: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: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::listhad anoperator[]. You may be tempted to write:that’s an O(n^2) algorithm! Ouch. Fortunately,
std::listdoes not haveoperator[]since it is assumed to be an efficient operation.