1

Is there a way to have a pointer to a function inside a referenced class?

I've tried replacing the reference to a class with another pointer, did not work.
I've also tried using -> instead of ., no luck.

class First {
  void FunToPointTo();
};
class Second {
  First &reference;
  void (*pointer)();
  Second(First &first);
};

Second::Second(First &first) : reference(first) {
  pointer = reference.FunToPointTo;
}

Error: cannot convert 'First::FunToPointTo' from type 'void (First::)()' to type 'void (*)()'

Now I am trying to somehow make my pointer into void (First::)(), but I don't know the exact syntax.

Help is greatly appreciated, also please excuse my lack of knowledge as I am just starting c++.

wallyk
  • 56,922
  • 16
  • 83
  • 148

1 Answers1

1

Your pointer type should be

void (First::*ptr)()

And assign with

&First::FunToPointTo

Since you need to specify the function is from class First.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
tomer zeitune
  • 1,080
  • 1
  • 12
  • 14
  • I don't need a general 'FunToPointTo' I need the one inside the referenced class. –  Feb 12 '19 at 14:49
  • @OgnjenIlic I know but if you really think what a function is it's a piece of code that takes argumentsand if it's not a static function it has a pointer to the object named "this" . in this case you call the function with the object you want to send to the "this" keyword like that : reference.*ptr(); . Someone already wrote this I see – tomer zeitune Feb 12 '19 at 14:55
  • @Quentin: See [this](https://en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions) – wallyk Feb 12 '19 at 15:00
  • 2
    @wallyk your article clearly states you should use the & operator for member functions look at the pointer to member functions section. It is a good article btw – tomer zeitune Feb 12 '19 at 15:03
  • @Quentin: tomer is quite right. I have deleted my earlier comment. – wallyk Feb 12 '19 at 15:51
  • @tomerzeitune: Thanks. I wonder why the rules are different for member functions? – wallyk Feb 12 '19 at 15:52
  • @wallyk I think they are treated more like members rather than functions. It does make some sense – tomer zeitune Feb 12 '19 at 16:22
  • @wallyk as with many other quirks, this might be a remnant of compatibility with C. – Quentin Feb 12 '19 at 16:38