-2

Can someone please give me a simple explanation of how to achieve or emulate run-time polymorphism in C.

Also, is this a valid example of runtime-polymorphism:

void fred(){
  printf("Fred here!\n"); 
}

void john(){
  printf("John here\n");
}

void barbara ( void (*function_ptr)() ){
  (*function_ptr)();
}

int main(){
  barbara (fred);
  barbara (john);
  return 0;
}

The function barbara dynamically calls either john() or fred(). Is this what runtime polymorphism exactly is?

jogojapan
  • 68,383
  • 11
  • 101
  • 131
CHID
  • 1,625
  • 4
  • 24
  • 43

1 Answers1

1

The function barbara dynamically calls either john() or fred().

No, it doesn't. barbara() calls whichever function you pass it as a parameter. barbara() does exactly the same thing no matter what you pass it -- namely, it executes the function that you pass as a parameter.

Is this what runtime polymorphism exactly is?

No. If barbara() looked at the parameter and changed its behavior based on some features (especially the type) of the parameter, then you'd be closer to polymorphism.

Caleb
  • 124,013
  • 19
  • 183
  • 272