Skip to content

Instantly share code, notes, and snippets.

@neocoin
Created March 24, 2012 18:46
Show Gist options
  • Save neocoin/2186548 to your computer and use it in GitHub Desktop.
Save neocoin/2186548 to your computer and use it in GitHub Desktop.
C++ function pointer example
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class Person
{
string name;
public:
Person(string name)
{
this->name = name;
printf("%s\n", name.c_str());
};
const char* getName()
{
return name.c_str();
}
const char* getName2()
{
return name.c_str();
}
};
typedef const char* (Person::*NamePointer)();
typedef const char* (Person::*NamePointer2)();
int main()
{
Person p = Person("John");
NamePointer methodPtr = &Person::getName;
printf("name is %s\n", (p.*methodPtr)());
Person *ptr = new Person("Alice");
printf("name is %s\n", (ptr->*methodPtr)());
NamePointer2 not_a_class_ptr = reinterpret_cast<NamePointer2>(&Person::getName);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment