As another Javascript developer learning C, I'm trying to implement a basic object.
UserStruct.h
#ifndef USERSTRUCT_H
#define USERSTRUCT_H
struct User {
int age;
int (* getAge)();
};
typedef struct User User;
int getAge(User);
User initUser(int);
#endif /* USERSTRUCT_H */
UserStruct.c
#include "./UserStruct.h"
int getAge(User this) {
return this.age;
}
User initUser(int age){
User user;
user.age = age;
user.getAge = getAge;
return user;
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "./UserStruct.h"
int main(int argc, char** argv) {
User user = initUser(15); // sets age to 15..
user.age = 2222;
printf("%d\n",user.getAge(1234)); // note the int passing here..
printf("%d\n",user.age);
return (EXIT_SUCCESS);
}
Questions!:
1. Can someone explain the syntax int (* getAge)(); inside the UserStruct definition?
2. getAge expects a User to be passed to it, how come it works with an int being passed in? This is especially strange as the implementation of getAge uses return this.age.
While I did figure out how to fix it, I'm still not sure why this behaves the way it does. (The solution is to pass a pointer of the User into getAge)
getAgefunction.Cto work as another language/paradigm you are accustomed to. You can't do OOP inC. You can't do overloading inC. You can't do polymorphism inC. you can't have member functions inC. Please stop trying to do so. UseCasCor use another language where you can use the paradigm you want.struct UsertogetAge(), not a pointer of any kind, and also to declareint (* getAge)();asint (* getAge)( struct User);instead.int (* getAge)(), that declaresgetAgeto be a pointer to a function taking an indeterminate number of arguments of indeterminate type, returning anint.