0

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? :)

kuk
  • 127
  • 1
  • 8
  • 1
    It's private. You can change the visibility. You can probably call it from a lambda that's created by another method of the class. – Joseph Larson Dec 03 '21 at 14:03
  • 1
    From inside `A::callError` you might do equivalent code... – Jarod42 Dec 03 '21 at 14:12
  • Why are you wanting to do this? Is it for unit tests? If the latter you can use some template trickery so as to avoid polluting the code you're testing. – Bathsheba Dec 03 '21 at 16:02

1 Answers1

2

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.

Rinat Veliakhmedov
  • 1,021
  • 1
  • 19
  • 36