• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 210
  • Last Modified:

pointer to member function

I am trying to create a function pointer in my class
that will point to different member function within the
same class.

My problem is that I cant figure out how to call the
function pointer.

Here is a very simple example:

class CDevice
      typedef void (CDevice::* EraseFnPtr)(int i);
      EraseFnPtr Erase;

      void Erase1(int i);
      void Erase2(int i);

      Erase = &CDevice::Erase1;

void CDevice::Erase1(int i)
      printf("Erase1 %d\n",i);

void main()
      CDevice Device;

I want the program to print out "Erase1 34".

But I get 2 compile errors that say
error C2065: 'Erase' : undeclared identifier
error C2297: '.*' : bad right operand

both regarding to this line:
----->      (Device.*Erase)(34);
This is in Visual C++ 5.0

So How do I call the Erase function pointer?

PS I dont want to change the way the class is set up, In other words I want the function pointer to be within the CDevice class.

  • 5
1 Solution
Problem: erase is a member.


the compiler is looking for a local or global variable called "Erase".  But there is none.  The erase you want is a member of the class try


Or better yet, define a member function that does the calling using the pointer.  Then call that member function here.  That hides the pointer-to-member stuff inside the class.   (Where I would say it belongs.  In most cases, I think I would make it entirely private to the class.)

Let me know if you have questions.
Wait a second.

>> PS I dont want to change the way the class is set up, In other words
>> I want the function pointer to be within the CDevice class

You don't want it to be within the class?  but you declared it there!  You can declare it outside the class, if that is what you want.   (But I wouldn't recommend it.)  I would move the typedef outside as well, in that case.
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Opps, ignore that last comment.  In my mind I added a "don't" that wasn't there.
vinny5Author Commented:

thanks neitod...
Im sorting of doing what you recommended I was just trying to create a simple
example to illustarte my question..  but  (Device.*Device.Erase)(34);
was exactly what I was looking for.


de nada
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now