2: Pointers to Functions

To define a pointer to a function use the syntax: “type (*name)(argument list);“

Now let’s say we have a function: int add(int a, int b) that adds a and b and returns the sum, now lets say that int (*add)(int, int) is a pointer to this function, we declare it by saying:

Code: C

int(*pfAdd)(int, int) = add;

so now if we use (*pfAdd)(1, 3) it will do the same thing as add(1, 3) and return 4.

Now a simple example of a program that uses pointers to functions to summarize the subject:

Code: C

/* start of ptf.c file */

#include <stdio.h>

int add(int a, int b){return a+b;}

int main(){int(*pfAdd)(int, int) = add;

printf(“the sum of 1 and 3 is %d\n”, (*pfAdd)(1, 3));

return0;}

/* end of ptf.c file */

Object Orinted Programming in C

Now begins the cool part, the actual purpose of this article… now, we are used to define classes and have them hold methods and members, this can also be done with a struct like this:

Code: C

/* start of example */

#define CLASS typedefstruct

CLASS {// add some pointers to functions that will be the methods without giving them values// add some public members if needed without values even if const} Car;

/* end of example */

But every function that we want to use MUST be declared before the structure, implementation can come later. To use a constructor and a destructor we will need to write the functions and then manually call them, or we can use a macro as well but still have to call it manually. Let’s finish this tutorial with an example: