Archived

This topic is now archived and is closed to further replies.

doctorsixstring

Member Function Pointers

Recommended Posts

I have two classes: CDog and CCat. I want CDog to contain a function pointer to a member function of CCat. I can't seem to get it to work quite right. Here is my code so far: CDog.h
  
class CDog
{
public:
	CDog();
	~CDog();
	static CCat* sm_pCat;

private:
	void LaunchFunction();
	void (CCat::*m_pRunFunction)();
};
  
CDog.cpp
  
#include "CDog.h"
#include "CCat.h"

CCat* CDog::sm_pCat = new CCat();

CDog::CDog() 
{
	m_pRunFunction = CCat::FunctionToPointTo;
}

CDog::~CDog() { /* ... */}

void CDog::LaunchFunction() { m_pRunFunction(); }		//error here

  
CCat.h
  
class CCat
{
public:
	CCat();
	~CCat();

	void FunctionToPointTo();
private:
};
  
I get an error saying that m_pRunFunction(); is not a valid function call. I'm pretty sure this code is almost right, but I can't seem to get it perfect. Any advice? -Mike [edited by - doctorsixstring on September 30, 2002 12:03:14 PM]

Share this post


Link to post
Share on other sites
Does anyone have any ideas? I just checked out the other thread on this topic ("point to class member function."), but I couldn''t find anything. I tried some of the code people posted over there, but none of it wor that worked out. Any ideas at all would be appreciated.

-Mike

Share this post


Link to post
Share on other sites
Auron    328
Unless you declare the method you want to point to as static, you can only call a method by pointer if you make the call through an instance of that class.

So in your case, you''d have to do something like this:

void CDog::LaunchFunction (CCat *Cat) { Cat->(*m_pRunFunction)(); }

I think that''s it. The syntax may be a little off but the point is more what matters here:

You must use an instance to call a method pointer otherwise the method has no data to work from when called.

-Auron

Share this post


Link to post
Share on other sites