CKS
CKS

Reputation: 3

How to call a private function using a function pointer inside a structure?

I am giving my sample code below. I want to call c::LocFn2 from the public function c::PubFn using function pointer. When I comment the line pp[1].fp(); code works perfectly. Please help me.

#include <iostream>

using namespace std;

class c
{
public:
    void PubFn();
private:
    struct p
    {
        int a;
        int b;
        int (c::*fp)();
    };
    static const p pp[];

    int LocFn1();
    int LocFn2();
};

void c::PubFn() {
    cout << "Val = "<< pp[1].a << "\n"; //It prints 3 correctly. 
    pp[1].fp(); //Here I wanna call c::LocFn2 using the function pointer.
}

int c::LocFn1() {
    cout << "This is loc fn1\n";
    return 0;
}
int c::LocFn2() {
    cout << "This is loc fn2\n";
    return 0;
}

const c::p c::pp[] =  { {1, 2, &c::LocFn1}, {3, 4, &c::LocFn2} };

int main()
{
    c obj;

    obj.PubFn();     
}

Upvotes: 0

Views: 49

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

Use the pointer-to-member operator ->*.

(this->*(pp[1].fp))();

The extra parentheses are necessary since the function call operator has a higher priority than the pointer-to-member operator does.

Upvotes: 1

Related Questions