Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I came across a c++ code on for_each() that i didnt understand. Here is the code:
C++
struct Class2
{
    void operator() (int a)
    {
        cout << a * 3 << " ";
    }
} ob1;

int main() {
  int arr[5] = { 1, 5, 2, 4, 3 };
  cout << "Multiple of 3 of elements are : ";
    for_each(arr, arr + 5, ob1);
}

What i dont understand is the bit where it says obj1; at the end of the struct. How does this work? And also how is for_each() able to take obj1 as a parameter?
Can someone please answer this question.

What I have tried:

I have tried finding more information, but i dont know what this is called
Posted
Updated 19-Sep-21 16:49pm
v2

As described at std::for_each - cppreference.com[^], the third parameter is a unary function. In the case above, the ob1 reference implies a call to the operator() function, so the result will be something like:
Multiple of 3 of elements are : 3 15 6 12 9 
 
Share this answer
 
v2
To answer the first part of your question, when something appears between the closing } and ; of a class/struct/union definition, it creates an instance of that class/struct/union with the specified name. It's the equivalent of
C++
struct Class2 {...};
Class2 ob1;
for those who are obsessed with typing fewer characters.
 
Share this answer
 
Comments
Richard MacCutchan 19-Sep-21 9:30am    
Yes, I forgot to answer that part.
They're called predicates and you don't need to instantiate the struct to use them.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900