Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it called operator overloading?

Tags:

c++

c++11

If the following class, Foo, is defined. It is said it overloads the unary ampersand (&) operator:

class Foo {
public:
   Foo* operator&() { return nullptr; }
};

I think in this case, (reglardless of the fact that you can get the address of such an object by means of std::addressof() and other idiomatic tricks) there is no way to access/choose the original unary ampersand operator that returns the address of the object called on, am I wrong?

By overloading however, I understand that there is a set of functions of which one will be selected at compile-time based on some criteria. But this thinking doesn't seem to match the scenario above.

Why is it then called overloading and not something else like redefining or replacing?

like image 523
ネロク・ゴ Avatar asked May 21 '17 20:05

ネロク・ゴ


People also ask

Why is it called an overload?

To overload is to load an excessive amount in or on something, such as an overload of electricity which shorts out the circuits. Overloading causes a "Too much!" situation.

What is called operator overloading?

In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.

What is meant by overloading and operator overloading?

Operator overloading allows operators to have an extended meaning beyond their predefined operational meaning. Function overloading (method overloading) allows us to define a method in such a way that there are multiple ways to call it.

Why are operators overloaded?

The need for operator overloading in C++It allows us to provide an intuitive interface to our class users, plus makes it possible for templates to work equally well with classes and built-in types. Operator overloading allows C++ operators to have user-defined meanings on user-defined types or classes.


1 Answers

Consider the following code:

int x;
Foo y;
&x; // built-in functionality
&y; // y.operator&();

We have two variables of different types. We apply the same & operator to both of them. For x it uses the built-in address-of operator whereas for y it calls your user-defined function.

That's exactly what you're describing as overloading: There are multiple functions (well, one of them is the built-in functionality, not really a "function") and they're selected based on the type of the operand.

like image 81
melpomene Avatar answered Oct 02 '22 16:10

melpomene