C++ Callback: How to use class member functions as callbacks?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: C++ Callback: How to use class member functions as callbacks?

  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    C++ language: How to use class member functions as callbacks?

    Q: How to use class member functions as callbacks?

    A: The problem is that every callback function has its own prototype, which determines the parameters that gets passed from the operating system to it.

    In C++ every member function has a hidden parameter - the so-called 'this' pointer which will be automatically passed to the function. C++ is able to associate a function with a particular instance of an object by means of the 'this' pointer. Member functions access member variables through the 'this' pointer...

    Code:
    class foo
    {
    public:
      void func() { integer_ = 0; }
    
    private:
      int integer_;
    };
    If you compile this code it will be compiled as

    Code:
    class foo
    {
    public:
      void func(foo* this) { this->integer_ = 0; }
    
    private:
      int integer_;
    };
    The operating system does not call callback functions through objects therefore it cannot handle the automatically added 'this' pointer... To get a member functions working as a callback routine you need to tell the compiler explicitly not to expect a 'this' pointer. To avoid the automatic 'this' pointer you have two possibilities:

    • Non-member functions
    • Static member functions

    Non-member functions are not part of a class and therefore do not have a 'this' pointer. Static member functions do not receive a 'this' pointer either...thus, if you want to use a member function as a callback routine you need to declare it as 'static'...


    Last edited by Andreas Masur; July 27th, 2005 at 12:58 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center