Possible Duplicate:
How can I simulate OO-style polymorphism in C?
I am newbie to C, C++ trying to achieve polymorphism in C (which is not supported by C) but is there any way to do it?
Where does my code go wrong? I have seen the code on this site which was bit complex for me to understand so modified it but its not working. Sorry if the question seems to be very basic or even foolish.
#include <stdio.h>
void tripple() {
printf("in tripple");
}
void square() {
printf("\nin sq");
}
int main() {
void *al;
al=&tripple;
(*al)();
al=□
(*al)();
return 0;
}
Frankly, you will do best to defer trying to achieve polymorphism in C until you are no longer a newbie at programming in C.
Your code is dubious (it doesn’t compile!). That should be
void (*al)(void);in yourmainand you should arguably include thevoidin the argument lists oftrippleandsquare. You don’t need the&in front of the function names in the assignments toal, though I don’t think it does any actual harm. (Beware though; there is a difference between using an array name and the address of an array name! That is:char a[10]; char *s = a; char (*t)[10] = &a;) You should also include a newline at the end of each message in each of these functions. Newlines at the beginning of a message are often (but not always) indicative of problems. Sometimes, it is OK to omit the newline at the end of a message, but not very often.Any polymorphism implemented in C will use function pointers. But you should not be trying to implement polymorphism in C until you are comfortable using function pointers without attempting polymorphism. I suppose it could be said to be ‘learning to swim by jumping in at the deep end’, but you’d do better to learn a language like C++ that supports polymorphism than trying to do it in C which doesn’t really do so.