Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ binary operator overloading

As per Deitel's 9ed C++ How to program, p. 439-440:

A binary operator can be overloaded as a non-static member function with one parameter or as a non-member function with two parameters (one of those parameters must be either a class object or a reference to a class object).

So, what other sort of object is there beside a class object or a reference to a class object? I cannot think of anything.

like image 915
J. Doe Avatar asked Apr 10 '18 04:04

J. Doe


2 Answers

So, what other object is there beside class object or a reference to a class object?

There are fundamental types defined by the language, such as int, double. Instances of fundamental types are also objects.

Let's say you have:

struct Foo { ... };

You can overload the operator+ function as non-member functions

Foo operator+(Foo , int);
Foo operator+(Foo& , int);
Foo operator+(int, Foo);
Foo operator+(int, Foo&);

etc. In all these cases, one of the arguments is a Foo or a Foo&. It can also be Foo const&. However, you cannot overload

int operator+(int, int);

since neither of the argument types is a class or a reference to a class.

like image 55
R Sahu Avatar answered Oct 02 '22 06:10

R Sahu


It means you can't (re)define the built-in operators like int operator+(int a, int b);. Note that the description is incomplete, one or both parameters can also be an enum.

like image 30
user657267 Avatar answered Oct 02 '22 08:10

user657267