0

I am looking at the documentation about std::for_each. (https://cplusplus.com/reference/algorithm/for_each/)

I cannot understand the way they are using the struct myclass because they are not declaring a variable in main to pass to for_each. This is the code:

#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>       // std::vector

struct myclass {           // function object type:
  void operator() (int i) {std::cout << ' ' << i;}
} myobject;

int main () {
  std::vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  std::cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myobject);
  std::cout << '\n';

  return 0;
}

My intuition is that

struct myclass {           // function object type:
  void operator() (int i) {std::cout << ' ' << i;}
} myobject;

equals to:

struct myclass {           // function object type:
  void operator() (int i) {std::cout << ' ' << i;}
};
myclass myobject;

So they are declaring the variable (as global) and defining the struct in the same statement. Is it correct?

Jason
  • 36,170
  • 5
  • 26
  • 60
ashamat
  • 1
  • 1
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of SO related posts. – Jason Aug 11 '22 at 09:18
  • 1
    Actually `myclass myobject;` is *defining* the variable `myobject`. Other than that your "intuition" is correct. – Some programmer dude Aug 11 '22 at 09:22
  • @ashamat Ok, I have added some dupes for your question. Check them out and you'll find the meaning. For example, [What does the name after the closing class bracket means?](https://stackoverflow.com/questions/17843145/what-does-the-name-after-the-closing-class-bracket-means). – Jason Aug 11 '22 at 09:23
  • @JasonLiam The questions you posted answer my question, I was not fining them probably because they are about `class` instead of directly about `struct`. Even if some of them then clarify also about `struct` in the answer. @Someprogrammerdude thanks for pointing out that mistake – ashamat Aug 11 '22 at 09:32
  • 1
    @ashamat - Essentially, the difference between `class` and `struct` is that you don't have to type `public:` at the start of a struct. So some people prefer to use a struct when everything is public anyway, like here. Otherwise they work the same. – BoP Aug 11 '22 at 11:46
  • @BoP `struct` also defaults to "public inheritance" where as `class` defaults to "private inheritance". But other than those two differences (default access and default inheritance) you are correct - no difference. – Jesper Juhl Aug 11 '22 at 12:25

0 Answers0