'C++ How to make function pointer to class method [duplicate]
I'm having trouble making a function pointer to a class method. I made a function pointer to a non-class method and it works fine.
int foo(){
return 5;
}
int main()
{
int (*pointer)() = foo;
std::cout << pointer();
return 0;
}
I tried to apply this to have an instance variable in a class be a function pointer.
This is the header file. It declares the private method Print which the variable method will point to.
class Game
{
public:
Game();
private:
void Print();
void (method)( void );
};
The Game constructor attempts to assign the pointer method to the address of the Print method. Upon compile, an error comes up at that line saying "error: reference to non-static member function must be called;". I don't know what that means. Whats the correct way of implementing this?
Game::Game( void )
{
method = &Game::Print;
}
void Game::Print(){
std::cout << "PRINT";
}
Solution 1:[1]
Just found out you can do
#include <functional>
#include <cassert>
using namespace std;
struct Foo {
int x;
int foo() { return x; }
};
int main() {
function<int(Foo&)> f = &Foo::foo;
Foo foo = { 3 };
assert(f(foo) == 3);
foo.x = 5;
assert(f(foo) == 5);
}
std::mem_fn() might work too: https://en.cppreference.com/w/cpp/utility/functional/mem_fn
Solution 2:[2]
1- Use the following syntax to point to a member function:
return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name;
2- keep in mind to have a pointer to member function you need to make it public.
in your case:
class Game
{
public:
Game(){}
void print() {
//todo ...
}
};
// Declaration and assignment
void (Game::*method_ptr) () = &Game::print;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
