S
subramanian100in
Consider the following program:
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Test
{
public:
Test(const string &str) : s(str) { }
void print()
{
cout << "from Test:rint() : " << s << endl;
return;
}
private:
string s;
};
int main()
{
list<Test *> ls;
Test zero("zero");
Test one("one");
Test two("two");
ls.push_back(&zero);
ls.push_back(&one);
ls.push_back(&two);
for_each(ls.begin( ), ls.end( ), mem_fun(Test:rint) );
return 0;
}
When I compile this program, I am getting the following compilation
error(as expected):
'Test:rint': function call missing argument list; use '&Test:rint'
to create a pointer to member
If I put
mem_fun(&Testrint)
it compiles fine.
Why should we pass the address of a member function here
(&Test:rint)?
Doesn't the function name Test:rint itself give a pointer ?
For example, a free global function name itself can be passed as
argument to for_each( ).
We don't need to pass the address of a global function(though passing
address of a global function is accepted).
What is the difference between passing member function and a global
function to for_each ?
Kindly explain.
Thanks
V.Subramanian
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Test
{
public:
Test(const string &str) : s(str) { }
void print()
{
cout << "from Test:rint() : " << s << endl;
return;
}
private:
string s;
};
int main()
{
list<Test *> ls;
Test zero("zero");
Test one("one");
Test two("two");
ls.push_back(&zero);
ls.push_back(&one);
ls.push_back(&two);
for_each(ls.begin( ), ls.end( ), mem_fun(Test:rint) );
return 0;
}
When I compile this program, I am getting the following compilation
error(as expected):
'Test:rint': function call missing argument list; use '&Test:rint'
to create a pointer to member
If I put
mem_fun(&Testrint)
it compiles fine.
Why should we pass the address of a member function here
(&Test:rint)?
Doesn't the function name Test:rint itself give a pointer ?
For example, a free global function name itself can be passed as
argument to for_each( ).
We don't need to pass the address of a global function(though passing
address of a global function is accepted).
What is the difference between passing member function and a global
function to for_each ?
Kindly explain.
Thanks
V.Subramanian