0

I have a C++ function pointer in a class ClassA:

void (ClassA::*funcPntr1)(void);

pointing to function:

void func();

by using assignment:

functPntr1 = &ClassA::func;

Now, i have another function pointer:

void (ClassA::*funcPntr2)(void);

I want funcPntr2 to point to the the function pointed by the funcPntr1. How do i do that?

I have tried this:

funcPntr2 = &(this->*funcPntr); //normally, i invoke the function pointer by (this->*funcPntr)()

But is wrong. I have tried many logical combinations, but doesn't seem to work.

5
  • 3
    funcPntr2 = funcPntr;? Commented Nov 9, 2013 at 16:54
  • But doesn't that just copy the pointer and not the function pointed to by the pointer? Commented Nov 9, 2013 at 16:59
  • If you want funcPntr2 to refer to the referent of funcPntr, then you want funcPtr2 to equal funcPntr. So funcPtr2 = funcPntr; Commented Nov 9, 2013 at 17:00
  • Wait, hang on, that does copy the pointer. It sounds like that's what you want. Do you want the function itself to also be copied? That will take a bit more than one line of code. Commented Nov 9, 2013 at 17:00
  • If its copying the pointer, then what happens when i change the function pointed by funcPntr1? Doesn't that change funcPntr2 too? Commented Nov 9, 2013 at 17:04

2 Answers 2

1

With assignment:

funcPntr2 = funcPntr;
Sign up to request clarification or add additional context in comments.

8 Comments

Doesn't that just copy the pointer and not the function pointed to by the pointer?
@Alterecho: Functions are not objects, and neither are member functions. There is no notion of "copying a function".
What happens when i change the function pointed by funcPntr after the assignment?
@Alterecho Then the old contents remain, as explained in my answer.
Function pointers work just like normal pointers. They point to whatever they point to. It doesn't matter whether you change the variables of any other pointers. funcPntr2 will just keep pointing to that same function.
|
1

If you want to assign the pointer which is currently assigned to it, it is a mere assignment, as others said (funcPntr2 = funcPntr).

If you want this assignment to persist, i. e. if you want that funcPntr2 always points to where funcPntr points to, even if the latter one changes, there is no way unless you change the definition.

You'd have to

  • have a void (ClassA::**funcPntr2)(void);
  • assign funcPntr2 = &funcPntr and
  • call (*funcPntr)().

As you talk about C++, I am not so familiar with; maybe you can do something with references.

1 Comment

That still depends on the first funcPntr. I am trying to make funcPntr2 independent funcPntr1 after the assignment. There is no way to do it then?

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.