Hi!
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 manish
{
int i;
public:
void man()
{
cout<<"\ntry to learn \n";
}
};
int main()
{
manish m, *n;
void manish:: *t =&manish::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 manish::man()’ without object
pcc.cpp:18: error: ‘t’ cannot be used as a function.
my question are following :
1: What I'm doing wrong in this code ?
2: How to make object pointer ?
3: How to make pointer to member function of a class and how to use them ?
Your code's confused in many ways. A pointer to a member method implies the passing of the object (this pointer). The declaration must include the signature of the method. So your declaration of the pointer is wrong and the call is wrong.
In your case, the pointer is of type:
(void)(manish::*p)(void);
The call must pass m in somehow. The syntax is:
(m.*p)();
Putting it all together, the code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
class manish
{
public:
void man()
{
std::cout << "man()" << std::endl;
}
};
int main()
{
manish m;
void (manish::*f)(void) = &manish::man;
(m.*f)();
return 0;
}
#include <iostream>
using namespace std;
class manish
{
int i;
public:
void man()
{
cout<<"\ntry to learn \n";
}
};
int main()
{
void (manish::*t)(void) =&manish::man; //making pointer to member function
manish m, *n;
n=&m;//confused is it object pointer
(n->*t)();
system("pause");
}