operator+

G

Gaijinco

I was perfectly sure that this code had to work:

#include <iostream>

int main()
{
std::cout << operator+(3,4);
return 0;
}

If I can overload the operator+() it means that there is a base
function defined by the language, right?
 
J

Jacek Dziedzic

Gaijinco said:
I was perfectly sure that this code had to work:

#include <iostream>

int main()
{
std::cout << operator+(3,4);
return 0;
}

If I can overload the operator+() it means that there is a base
function defined by the language, right?

Note that you _can't_ overload operator+() for int.

- J.
 
A

Alf P. Steinbach

* Gaijinco:
I was perfectly sure that this code had to work:

#include <iostream>

int main()
{
std::cout << operator+(3,4);
return 0;
}
Nope.


If I can overload the operator+() it means that there is a base
function defined by the language, right?

No.

You can overload operator+ for enum and class type arguments, and for
enum or class type reference arguments, but then there's no built-in
implementation. I.e. there's no "base" function you can base your
implementation on. Note for enums: in the case of enum arguments to +,
without a user-defined operator+ for that type, the arguments are
promoted to int or higher and the + operator for that integer type is used.

You can not overload operators for built-in types such as int, nor for
pointer types.
 
R

Ron Natalie

Jacek said:
Note that you _can't_ overload operator+() for int.
Further, you can't get at the builtin operator implementations
by trying to access them as overload functions. It's primarily
for this reason that funky little template functions like "less"
exist.
 
G

Gaijinco

I always assumed that when I right in a code

a + b

What really happened is that the language rewrote the code to

operator+(a,b)

and that because of it, it was possible to use the function notation
for all operators.

So is there anyway in which I can use the function notation instead of
the classic notation?
 
N

Nate Barney

Gaijinco said:
I always assumed that when I right in a code

a + b

What really happened is that the language rewrote the code to

operator+(a,b)

and that because of it, it was possible to use the function notation
for all operators.

So is there anyway in which I can use the function notation instead of
the classic notation?

Like Ron suggested, use STL functors. In this case, something like this
might work:

#include <functional>

int main()
{
std::plus<int> p;
int a=1,b=2;

int c = p(a,b);

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top