Is it not possible to call C++ operators manually?

Arvin picture Arvin · Aug 29, 2011 · Viewed 9k times · Source

I'm trying to understand operators in C++ more carefully.

I know that operators in C++ are basically just functions. What I don't get is, what does the function look like?

Take for example:

int x = 1;
int y = 2;
int z = x + y;

How does the last line translate? Is it:

1. int z = operator+(x,y);

or

2. int z = x.operator+(y);?

When I tried both of them, the compiler errors. Am I calling them wrong or are operators in C++ not allowed to be called directly?

Answer

In silico picture In silico · Aug 29, 2011

Using C++ standardese, the function call syntax (operator+(x, y) or x.operator+(y)) works only for operator functions:

13.5 Overloaded operators [over.oper]

4. Operator functions are usually not called directly; instead they are invoked to evaluate the operators they implement (13.5.1 - 13.5.7). They can be explicitly called, however, using the operator-function-id as the name of the function in the function call syntax (5.2.2). [Example:

    complex z = a.operator+(b); // complex z = a+b;
    void* p = operator new(sizeof(int)*n);

—end example]

And operator functions require at least one parameter that is a class type or an enumeration type:

13.5 Overloaded operators [over.oper]

6. An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

That implies that an operator function operator+() that only takes ints cannot exist per 13.5/6. And you obviously can't use the function call syntax on an operator function that can't exist.