Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Address of Methods

Status
Not open for further replies.

tcollins

Programmer
Sep 12, 2000
34
US
Also, does anyone know how to take the Address of a Method? I have a method inside a C++ Class that another function needs to call as a function pointer.
 
Just use the method name without the parameters. If it is within a class, make the method static.
 
Here is a proof of concept that shows method pointers in use. The use of static is not required.

Matt

Code:
#include <iostream.h>

class c1{
public:
	c1::c1(){}
	void sample1();
	void sample2();
	void sample3();
	void sample4();
	void sample5();
	void sample6();

};

void c1::sample1(){cout<<&quot;sample1\n&quot;;}
void c1::sample2(){cout<<&quot;sample2\n&quot;;}
void c1::sample3(){cout<<&quot;sample3\n&quot;;}
void c1::sample4(){cout<<&quot;sample4\n&quot;;}
void c1::sample5(){cout<<&quot;sample5\n&quot;;}
void c1::sample6(){cout<<&quot;sample6\n&quot;;}

class c2{
public:
	c2::c2( void(c1::*ptr)() ):method_ptr(ptr){};
	void setmethod(void(c1::*ptr)());
	void fire();
private:

	void (c1::*method_ptr)();  
};


class c3{
public:
	c3::c3():method_ptr(fxna){};
	void setmethod(int x);
	void fxna(){cout<<&quot;fxna\n&quot;;}
	void fxnb(){cout<<&quot;fxnb\n&quot;;}
	void fxnc(){cout<<&quot;fxnc\n&quot;;}
private:

	void (c3::*method_ptr)();  
};

void c2::fire(){c1 temp;(temp.*method_ptr)();}
void c2::setmethod(void(c1::*ptr)()){method_ptr=ptr;}
void c3::setmethod(int x){
	switch(x)
	{ 
	case 1:method_ptr = fxna;break;
	case 2:method_ptr = fxnb;break;
	case 3:
	default:method_ptr = fxnc;break;
	}
}


int main()
{
	c2 mc2(&c1::sample1);

	mc2.fire();
	mc2.setmethod(&c1::sample2);
	mc2.fire();
	mc2.setmethod(&c1::sample3);
	mc2.fire();
	mc2.setmethod(&c1::sample4);
	mc2.fire();
	mc2.setmethod(&c1::sample5);
	mc2.fire();
	mc2.setmethod(&c1::sample6);
	mc2.fire();

	c3 mc3;

	cout<<&quot;\n\n\n\nbeginning\n\n\n\n&quot;;
	mc3.setmethod(1);
	mc3.setmethod(2);
	mc3.setmethod(3);



	return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top