Hey guys today I'm going to be showing you how to use function pointers from the C++11 standard library, this has a wide range of applications, I have used this before to create state machines and many other things.

Firstly here is the entire code:
File: DemiGod.h

#ifndef DEMIGOD_H
#define DEMIGOD_H
#include <functional>
#include <vector>
class DemiGod
{
public:
DemiGod();
std::vector<std::function<void()>> vector_of_functions;

protected:
private:
void functionA();
void functionB();
void functionC();
};

#endif //DEMIGOD_H


File: DemiGod.cpp

#include "demigod.h"

DemiGod::DemiGod()
{
auto functionAPtr = std::bind(&DemiGod::functionA,this);
auto functionBPtr = std::bind(&DemiGod::functionB,this);
auto functionCPtr = std::bind(&DemiGod::functionC,this);

vector_of_functions.emplace_back(functionAPtr);
vector_of_functions.emplace_back(functionBPtr);
vector_of_functions.emplace_back(functionCPtr);
}

void DemiGod::functionA()
{
std::cout << "I Like Turtles" << std::endl;
}

void DemiGod::functionB()
{
std::cout << "I Like Monkeys" << std::endl;
}

void DemiGod::functionC()
{
std::cout << "I Like Linux" << std::endl;
}



File:main.cpp

#include <iostream>
#include "demigod.h"
using namespace std;

int main()
{
DemiGod myGod;
myGod.vector_of_functions.at(0)();
myGod.vector_of_functions.at(1)();
myGod.vector_of_functions.at(2)();
return 0;
}



-----------------------------------------------------------
Now lets get into what he have done here.

in the DemiGod header we included two headers, <vector> and <functional>. functional is a new STL class for creating function pointers and vector is just a normal vector.

Vector takes a template parameter of the type we are using, in this case we are using functional which also takes a template parameter of the functions return type followed by the parameter list. For example void(int x); specifies that your function returns void and takes one parameter of int x.

Next we simply declare our functions as part of the class.

Now in the constructor of our class is where the business happens, I let C++ determine the return type of std::bind (Which in this case should always return a type of void) because it is possible to do this with function template specialization which would just make a mess of our code, so thus i use auto and let C++ type cast it, but as i said you could be explicit.

std::bind takes two parameters in our case (Although the second parameter is a variadic template)

a reference to the function, NOTE: YOU MUST resolve the function to the scope of the class it belongs to) and a reference to the class itself.

next we emplace these into the end of our vector

finally in main.cpp we call each of these functions with no parameter type.

If anyone has any questions please comment and ill try to clear it up as best as I can

Cheers