Search code examples
c++ooppointer-to-member

How to call private member function by using a pointer


Rookie question:

So there is this class

class A
{
private:
    void error(void);
public:
    void callError(void);
};

And I would like to call error from callError using a pointer.

I can achieve calling a public function from main using a pointer.

int main(void)
{
    void (A::*abc)(void) = &A::callError;
    A test;

    (test.*abc)();
    return (0);
}

However, I cannot find a way how to call error function from callError using a pointer. Any tips? :)


Solution

  • Add a public method to your class that returns a pointer to the private function:

    class A
    {
    private:
        void error(void);
    public:
        void callError(void);
    
        auto get_error_ptr() {
            return &A::error;
        }
    };
    
    int main(void)
    {
        void (A::*abc)(void) = &A::callError;
        A test;
    
        (test.*abc)();
    
        void (A::*error_ptr)(void) = test.get_error_ptr();
        (test.*error_ptr)();
    
        return (0);
    }
    

    But I wouldn't suggest actually using this kind of code in a real application, it is extremely confusing and error-prone.