Computer Science, asked by royrishabh5212, 1 year ago

What do you mean by operator overloading in c++

Answers

Answered by bgcipetlko
0

In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +.

Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.

Answered by Hacket
0

It means when you're working with custom data types and objects, you can redefine what '+', '-', '*', '/' and various other operators mean.

It is necessary when dealing with template code, as in standard template library.

Let's say you have a "mathematical expression" object -- one that isn't just a number, but rather a bunch of numbers and operators together, so something like

x+57-y+22=0

would all be represented in the object.

Obviously this expression can be added, subtracted, multiplied, divided, and have other operations done to it.

Now let's say for some reason you need to call an STL function on it, like a summing algorithm.  Your expression object isn't a number so the standard definition of the operators doesn't work.  Since template types aren't defined as being inherited from some other kind of object, they use operators for manipulation.

Problem:  even though you know how to +, -, * or / your expression, the computer doesn't know what to do when you say exprA + exprB.

Operator overloading is how you tell the computer what to do.

There are also cases where the computer does know what to do, but it's wrong.  Like, for instance, when assigning one object equal to another.  If the object contains a pointer (including an array), instead of making a copy of the array the computer will just copy over the pointer, so if you manipulate the array in one object it will screw with the other object.  BOO!  DO NOT WANT!

Overloading the '=' operator lets you avoid problems like that.  (Of course, I fully expect a few comments saying "but pointers are a terrible way to deal with arrays!"  Maybe, but they're probably the fastest and least resource-hungry way, too.)

Operator overloading is a convenient way to make use of already-written template code.  It is consequently a powerful tool.  Unfortunately there are a lot of things you can do wrong with it, and they're probably harder to debug than other stuff.

Thanks for asking

Similar questions