1

I am trying to understand function pointers and I have the following test code:

#include <iostream>

using namespace std;

class Test {
public:
    void test_func() {
        cout << "Test func called.";
    }
};

void outer_test_func(Test &t, void (Test::*func)()) {
    (t.*func)();
}

int main(int argc, char *argv[]) {
    auto t = Test();
    outer_test_func(t, &Test::test_func);
}

This works. But from what I understand Test::test_func and &Test::test_func both result in pointers. So why can't I use the former instead of the latter? If I try it g++ complains.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
K G
  • 1,715
  • 6
  • 21
  • 29
  • 3
    You are playing around with pointers to **non-static member functions**. They are a different beast. – StoryTeller - Unslander Monica Dec 06 '17 at 14:28
  • 2
    In what situation does `Test::test_func` result in a pointer? Without any confirming examples, it's just an assumption. – chris Dec 06 '17 at 14:29
  • As you will recall, member functions are members of an object. Without the "this" parameter, they wouldn't make any sense. Rewrite the example using private: std::string m_testmessage, and print that, and imagine how that would work without the Test &t object to carry the member data. – Kenny Ostrom Dec 06 '17 at 14:30
  • _"So why can't I use the former instead of the latter? If I try it g++ complains."_ Didn't you just answer your own question? You can't use it because it's not valid syntax in that context as defined by the language, and that's why the compiler complains. – underscore_d Dec 06 '17 at 14:31
  • 1
    Possible duplicate of [Function pointer to member function](https://stackoverflow.com/questions/2402579/function-pointer-to-member-function) – underscore_d Dec 06 '17 at 14:32
  • 1
    The name of a free function easily decays to a pointer, because that's how they work in C. Member functions are C++ only and designed differently. – Bo Persson Dec 06 '17 at 14:39
  • If you are using C++11, I highly recommend learning how to use std::function – Clonk Dec 06 '17 at 14:40

1 Answers1

2

But from what I understand Test::test_func and &Test::test_func both result in pointers.

Test::test_func is not a valid syntax for creating pointer to member function, nor pointer to data members. It has never been a valid C++ syntax.

From cppreference (emphasis mine),

A pointer to non-static member object m which is a member of class C can be initialized with the expression &C::m exactly. Expressions such as &(C::m) or &m inside C's member function do not form pointers to members.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141