c - Functions as members of structs -


as javascript developer learning c, i'm trying implement 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 15..    user.age = 2222;    printf("%d\n",user.getage(1234)); // note int passing here..    printf("%d\n",user.age);   return (exit_success); } 

questions!:
1. can explain syntax int (* getage)(); inside userstruct definition?
2. getage expects user passed it, how come works int being passed in? strange implementation of getage uses return this.age.

while did figure out how fix it, i'm still not sure why behaves way does. (the solution pass pointer of user getage)

c not object oriented language existed before object, example demonstrating can used objects.

  • int (* getage)() function pointer, function takes parameters () , returns int, specify function takes no parameter should defined (void)

  • getage "method" of class user needs object instance, in object languages syntax user.getage() passes implicitly this first argument, in c it's explicit: getage(user).

the problem int can used pointer means user.getage(1234) use 1234 address user take second int field address fuction getage , jump address.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -