Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading

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

What are the pros & cons (if any) ?

like image 731
Nikhil Garg Avatar asked Nov 28 '22 01:11

Nikhil Garg


2 Answers

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.

like image 108
Evan Teran Avatar answered Dec 04 '22 20:12

Evan Teran


The initial driver is usually maths. Programmers want to add vectors and quaternions by writing a + b and multiply matrices by vectors with M * v.

It has much broader scope than that. For instance, smart pointers look syntactically like normal pointers, streams can look a bit like Unix pipes and various custom data structures can be used as if they were arrays (with strings as indexes, even!).

The general principle behind overloading is to allow library implementors to enhance the language in a seamless way. This is both a strength and a curse. It provides a very powerful way to make the language seem richer than it is out of the box, but it is also highly vulnerable to abuse (more so than many other C++ features).

like image 31
Marcelo Cantos Avatar answered Dec 04 '22 20:12

Marcelo Cantos