Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator() parenthesis - operator Type() vs Type operator() [duplicate]

Tags:

c++

What's the difference if any?

For example: int operator() vs operator int()

I'm looking for an answer with "official" C++ documentation.

like image 398
Bob Avatar asked Jul 21 '26 19:07

Bob


2 Answers

The first (int operator()(...)) is a function call operator, which turns an object into a function object that can be called like a function. This specific operator returns an int, the argument part is missing.

Example:

struct Foo
{
    int operator()(int a, int b)
    {
        return a + b;
    }
};

...

Foo foo;
int i = foo(1, 2);  // Call the object as a function, and it returns 3 (1+2)

The other (operator int()) is a conversion operator. This specific one allows an object to be implicitly (or explicitly if declared explicit) converted to an int. It must return an int (or whatever type is used, user-defined types like classes or structures can be used as well).

Example:

struct Bar
{
    operator int()
    {
        return 123;
    }
};

...

Bar bar;
int i = bar;  // Calls the conversion operator, which returns 123

The conversion operator is the opposite of a one-argument constructor.

like image 65
Some programmer dude Avatar answered Jul 23 '26 08:07

Some programmer dude


There's a huge difference.

T operator() is a call operator, so you could 'call' your class like this:

class stuff {
    // init etc
    int operator()() {
        return 5;
    }
};

auto A = stuff(); // init that
cout << A() << endl; // call the object

operator T() is for converting an object of your class to type T, so you could do this:

class stuff {
    operator int() {
        return 5;
    }
};

auto A = stuff();
cout << int(A) << endl;

The conversion could be strictly explicit and explicit or implicit, like the one above.

like image 43
ForceBru Avatar answered Jul 23 '26 09:07

ForceBru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!