/** * @file funcpointer.cpp * @brief This file demonstrates the usage of function pointers in C++. * * The code defines two struct types, Student and Employee, and a linked list * implementation using function pointers. It showcases how function pointers * can be used to print the data stored in the linked list nodes. The main * function adds nodes to the linked list, prints the data using function * pointers, and measures the elapsed time. Finally, it cleans up the memory * allocated for the linked list. */ #include #include #include #include // Define two different struct types. typedef struct Student { char name[50]; static void print(void *node) { Student *s = (Student *)node; printf("Student:\n"); printf("Name: %s\n", s->name); } } Student; typedef struct Employee { int id; static void print(void *node) { Employee *e = (Employee *)node; printf("Employee:\n"); printf("Employee ID: %d\n", e->id); } } Employee; // Functions to print the data. enum { STUDENT, EMPLOYEE } type; // Define a node which can hold either of the structs and a function pointer to // print them. typedef struct node { void *data; int type; void (*print)(void *); } Node; int main() { Node arr[2]; int nodeCount = 0; Student s1 = {"Alice"}; arr[nodeCount].data = &s1; arr[nodeCount].print = Student::print; arr[nodeCount].type = STUDENT; nodeCount++; Employee e1 = {25}; arr[nodeCount].data = &e1; arr[nodeCount].print = Employee::print; arr[nodeCount].type = EMPLOYEE; nodeCount++; // Print loop using if-else for (int i = 0; i < nodeCount; i++) { if (arr[i].type == STUDENT) { Student::print(arr[i].data); } else { Employee::print(arr[i].data); } } // Print loop using function pointers for (int i = 0; i < nodeCount; i++) { arr[i].print(arr[i].data); printf("\n"); } return 0; }