Call an object method: Difference between revisions

Added C implementation
No edit summary
(Added C implementation)
Line 167:
myClassObject.myFunction(some parameter);
</lang>
=={{header|C}}==
C has structures and it also has function pointers, which allows C structures to be associated with any function with the same signature as the pointer. Thus, C structures can also have object methods.
<lang C>
#include<stdlib.h>
#include<stdio.h>
 
typedef struct{
int x;
int (*funcPtr)(int);
}functionPair;
 
int factorial(int num){
if(num==0||num==1)
return 1;
else
return num*factorial(num-1);
}
 
int main(int argc,char** argv)
{
functionPair response;
 
if(argc!=2)
return printf("Usage : %s <non negative integer>",argv[0]);
else{
response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
}
return 0;
}
</lang>
And yes, it works :
<pre>
$ ./a.out 10
 
Factorial of 10 is 3628800
</pre>
=={{header|C++}}==
<lang cpp>// Static
Line 1,878 ⟶ 1,915:
{{omit from|BASIC|not OO}}
{{omit from|bc}}
{{omit from|C|not OO}}
{{omit from|dc}}
{{omit from|GUISS}}
503

edits