4

I am defining function pointer inside a class and trying to access it through an instance of the class but it shows an error.

Here is the code:

 1 #include<stdio.h>
 2 
 3 class pointer {
 4 public:
 5    int (pointer::*funcPtr)(int);
 6    pointer() {
 7       funcPtr = &pointer::check;
 8    }
 9 
10 
11    int check(int a)
12    {
13       return 0;
14    }
15 
16 };
17 
18 int main()
19 {
20    pointer *pt=new pointer;
21    return (pt->*funcPtr)(3);
22 }

It shows a compile time error:

checkPointer.cpp:21:15: error: ‘funcPtr’ was not declared in this scope

please help me.

Thank You in advance.

1
  • +1 Welcome to Stack Overflow! Thank you for providing a complete, concise testcase. See sscce.org for reasons why I wish everyone did that. Commented Mar 30, 2012 at 16:19

3 Answers 3

2

The issue here is that funcPtr is declared inside of pt, so you need to use the name pt twice - once as the left-hand side of the pointer-to-member-selection, and once to choose the pointer class from which to select funcPtr:

(fn->*(fn->funcPtr))(3);

The reason for this is that you could potentially call the function pointed at by the funcPtr member of one instance of pointer on another instance of pointer.

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

@fschmitt- I don't believe so. funcPtr is the name of the data member of pt that I want to select. You don't need to use scope resolution to select a pointer-to-member-function.
1

I think you meant

pt->*(pt->funcPtr)(3);

Comments

1

I'm going to suggest that you follow the instructions from the C++ FAQ. Normally, that author avoids typedefs and #defines, but for this case he makes an exception:

#define CALL_MEMBER_FN(object,ptrToMember)  ((object).*(ptrToMember))
…
    CALL_MEMBER_FN(*pt, pt->funcPtr)(3)

P.s. Even if you don't follow those instructions, do read that page. It has loads of useful information about pointers to member functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.