Archived

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

Wavarian

Pointer to class method

Recommended Posts

Wavarian    850
Hey there, i''m trying to find out how to call the method of a particular instance of a class within another, such that whenever the method is called through a function pointer, the method will still be associated with that instance. eg:
class cTEMPA{
   int count;

public:
   cTEMPA(){count = 0;}
   void incCount(){count++;}
   int getCount(){return count;}
};

class cTEMPB{
   void (cTEMPA::*p)();

public:
   cTEMPB(void (cTEMPA::*&d)()){p = d;}
   void update(){
      cTEMPA instance;
      (instance.*p)()
   }
}

void main(){
   cTEMPA a;
   cTEMPB b(a.incCount);

   a.incCount();
   a.getCount(); // should return 1

   b.update();
   a.getCount(); // should return 2

}
please note that im not expecting the above to work, its just a general idea of how i need this to work. Any ideas/suggestions/samples or advice on how i might accomplish this? Thanks again,

Share this post


Link to post
Share on other sites
Fruny    1658
You need to keep the pointer and the instance separate until it is time to do the call. There is no way of passing around a bound pointer-to-member.

For a possible solution, you could check out Boost''s function objects, and particularly boost::function and boost::bind.

Your functions will have to be designed around them though. They are not compatible with APIs that expect ''ordinary'' function pointers.

But then, pointers-to-members are not compatible with such APIs either, so you''re not losing anything.

Another option would be to switch to a language that supports such constructs


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites