> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/all-about-c++/basics-of-pointers-to-member-functions.md).

# Basics of Pointers to Member Functions

A pointer to a member function is a special type of pointer that can point to a function that belongs to a class. The syntax is different from regular function pointers because it needs to account for the class it belongs to.

### Declaration Syntax

```cpp
return_type (ClassName::*pointerName)(parameter_types);
```

For example:

```cpp
void (MyClass::*ptr)();  // Pointer to a member function of MyClass that returns void and takes no parameters
int (MyClass::*ptr2)(int, double);  // Pointer to a member function of MyClass that returns int and takes int and double parameters
```

### Using typedef or using for Clarity

You can use `typedef` or `using` to create aliases for these pointer types:

```cpp
typedef void (MyClass::*SimpleFunc)();
// or
using SimpleFunc = void (MyClass::*)();
```

### Assigning and Calling Member Function Pointers

### Assigning

```cpp
class MyClass {
public:
    void foo() { std::cout << "foo" << std::endl; }
};

SimpleFunc ptr = &MyClass::foo;
```

### Calling

To call a member function through a pointer, you need an object of the class:

```cpp
MyClass obj;
(obj.*ptr)();  // Call foo() on obj

MyClass* pObj = new MyClass();
(pObj->*ptr)();  // Call foo() through pointer to obj
```

### Arrays of Member Function Pointers

You can create arrays of member function pointers:

```cpp
SimpleFunc funcArray[] = {&MyClass::foo, &MyClass::bar, &MyClass::baz};

// To call:
for (auto func : funcArray) {
    (obj.*func)();
}
```

### Structs with Member Function Pointers

As in your example, you can create structs that pair strings with member function pointers:

```cpp
struct Command {
    std::string name;
    SimpleFunc func;
};

Command commands[] = {
    {"FOO", &MyClass::foo},
    {"BAR", &MyClass::bar}
};

// To use:
for (const auto& cmd : commands) {
    if (cmd.name == "FOO") {
        (obj.*(cmd.func))();
        break;
    }
}
```

### Using with std::function

You can use `std::function` to create a more flexible interface:

```cpp
std::function<void(MyClass&)> func = &MyClass::foo;
func(obj);  // Calls obj.foo()
```

### Template Member Function Pointers

You can create template member function pointers:

```cpp
template<typename T>
void (MyClass::*templatePtr)(T) = &MyClass::templateFunc;

// Usage:
(obj.*templatePtr<int>)(5);
```

### Practical Example: Command Pattern

Here's a practical example using the Command pattern:

```cpp
class Commander {
public:
    void attack() { std::cout << "Attacking!" << std::endl; }
    void defend() { std::cout << "Defending!" << std::endl; }
    void retreat() { std::cout << "Retreating!" << std::endl; }

    using Command = void (Commander::*)();

    void executeCommand(const std::string& commandName) {
        static const std::unordered_map<std::string, Command> commandMap = {
            {"ATTACK", &Commander::attack},
            {"DEFEND", &Commander::defend},
            {"RETREAT", &Commander::retreat}
        };

        auto it = commandMap.find(commandName);
        if (it != commandMap.end()) {
            (this->*(it->second))();
        } else {
            std::cout << "Unknown command!" << std::endl;
        }
    }
};

// Usage:
Commander commander;
commander.executeCommand("ATTACK");  // Outputs: Attacking!
```

This example demonstrates how to use member function pointers with a map for easy command execution based on string input.

Remember, while powerful, member function pointers can make code more complex. Use them judiciously, typically when you need runtime polymorphism without inheritance or when implementing certain design patterns.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/all-about-c++/basics-of-pointers-to-member-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
