Home > Development > C# Delegates in C++ using Function Pointers

C# Delegates in C++ using Function Pointers

Well we are back again with just a short and simple post. In C# you can declare a delegate using the delegate keyword. An example might be if we want to check if a student matches some criteria.
i.ie delegate void StudentMatch(Student student);

The above stament declares a delegate aka function pointer with a return type of bool and takes a parameter of student.
This allows us to create a method on the on some other entity that may take a student and a studentmatch delegate and can anser any question about wether a student is valid. The main use of delegates or function pointers is to provide extension points in our code so it perform operations that were not thought of at that point in time. We could use plain OO to achieve this but it is more work in some cases.

In C++ we have function pointers. Here is some code showing you the syntax of declaring the same snippet.

struct Student{
    int* id;

bool studentHasIdGreaterThanZero(Student& student);
void printMatchesPredicate(bool (*fp)(Student&), Student& student);

void printMatchesPredicate(bool (*fp)(Student&), Student& student){
        cout << "We have a match" << endl;

bool studentHasIdGreaterThanZero(Student& student){
    return *(student.id) > 0;

As you can see we invoke the function pointer just as with C# using normal method invokation syntax.
bool (*fp)(Student&) declare the function pointer. not as nice as C# but achieves the same effect.


Categories: Development Tags: , , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: