Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a class member function be invoked without an object?

I was learning the history about Lambda’s in C++ and saw the following code (which is not lambda) but I am surprised how it Works

struct Printer{
void operator() (int x) const{
    std::cout << x << '\n';
 }
};

 int main(){
   std::vector <int> vint;
   //doing it the C++ 03 way
    vint.push_back(1);
    vint.push_back(7);

 std::for_each(vint.begin(),vint.end(), Printer());

}

How is the Printer() call in the for_each function working?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Printer() is an instance of the Printer class. It will result in a temporary object of type Printer which is passed to std::for_each.

This is the object on which operator() is called by std::for_each internally.

Without an object of type Printer, it is not possible to call the operator() member function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading