Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading