I have a question regarding the syntax of how to call a functor in C++. In the code below, why do the first 2 examples work whilst the 3rd and 4th attempt do not?
Also I can call ob (100);
and it will output 300
, but why can't I call Class(100)
and have it output 300
? Is there any way to use the overloaded operator ()
without instantiating a new object?
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct Class
{
void operator() (int a)
{
cout << a * 3 << " ";
}
} ob;
int main()
{
int arr[5] = { 1, 5, 2, 4, 3 };
cout << "Multiple of 3 of elements are : ";
for_each(arr, arr + 5, Class());
cout << endl;
for_each(arr, arr + 5, ob);
cout << endl;
// Why do these not work???
for_each(arr, arr + 5, Class);
for_each(arr, arr + 5, ob());
}