c++function-pointerspointer-to-membermember-functions

How can I create a pointer to a member function and call it?


How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:

class Dog : Animal
{
    Dog ();
    void bark ();
}

…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…

Also, if possible, I’d like to invoke the constructor via a pointer as well:

NewAnimalFunction pNew = &Dog::Dog;
Animal* pAnimal = (*pNew)();    

Is this possible, and if so, what is the preferred way to do this?


Solution

  • Read this for detail :

    // 1 define a function pointer and initialize to NULL
    
    int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
    
    // C++
    
    class TMyClass
    {
    public:
       int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
       int DoMore(float a, char b, char c) const
             { cout << "TMyClass::DoMore" << endl; return a-b+c; };
    
       /* more of TMyClass */
    };
    pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
    
    // Calling Function using Function Pointer
    
    (*this.*pt2ConstMember)(12, 'a', 'b');