I'm new to c++ . I want to know about object pointer and pointer to member function . I wrote a code which is following:
code :
#include <iostream>
using namespace std;
class golu
{
int i;
public:
void man()
{
cout<<"\ntry to learn \n";
}
};
int main()
{
golu m, *n;
void golu:: *t =&golu::man(); //making pointer to member function
n=&m;//confused is it object pointer
n->*t();
}
but when i compile it it shows me two error which is following:
pcc.cpp: In function ‘int main()’:
pcc.cpp:15: error: cannot declare pointer to ‘void’ member
pcc.cpp:15: error: cannot call member function ‘void golu::man()’ without object
pcc.cpp:18: error: ‘t’ cannot be used as a function.
my question are following :
Please explain me these concept.
A member function pointer has the following form:
R (C::*Name)(Args...)
Where R
is the return type, C
is the class type and Args...
are any possible parameters to the function (or none).
With that knowledge, your pointer should look like this:
void (golu::*t)() = &golu::man;
Note the missing ()
after the member function. That would try to call the member function pointer you just got and thats not possible without an object.
Now, that gets much more readable with a simple typedef:
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
Finally, you don't need a pointer to an object to use member functions, but you need parenthesis:
golu m;
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
(m.*t)();
The parenthesis are important because the ()
operator (function call) has a higher priority (also called precedence) than the .*
(and ->*
) operator.
Two errors corrected here:
int main()
{
golu m, *n;
void (golu::*t)() =&golu::man;
n=&m;
(n->*t)();
}
n->*t();
is interpreted as (n->*(t()))
while you want (n->*t)()
;If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With