Sunday, July 12, 2009

Can anyone explain what is the main idea behind pointer to function in C++ and whats a use of it?

whats the reason we use pointer to function e.g int* funcction() .just whats the main use of it?

Can anyone explain what is the main idea behind pointer to function in C++ and whats a use of it?
This is generally the C equivalent of polymorphism. Without object-oriented features in the language, you can have virtual member functions in a struct by making them function pointers. Then, different instances of that struct can have different values for those function pointers.





e.g. you want to have a "Shape" struct, and you put in a function pointer named "draw". For circles you have the draw function pointer set to a function named "draw_circle" and for squares you have the draw function pointer set to a function named "draw_square". Then you can walk a list of shapes and call the draw() function pointer on each, not caring what each one is.


No comments:

Post a Comment