Originally Posted by
patishi
But how can i link the getAge pointer to the returnInt() function, so that it will be returning the age inside the Person ?
And how can I create some sort of constructor that will automatically initialize all the variables inside a Person struct?
You can't make construction automatic, but you can make a constructor function and make sure you call it. If the struct is opaque, then you can also be reasonably sure that the user will have to use your constructor (similar to fopen and fclose operate on FILE *).
If the object is not-opaque then of course there is no true information hiding, but for most purposes in C this is probably adequate. If not consider C++.
Person.h example
Code:
#pragma once
#define PERSON_STRMAX (1000)
typedef struct Person Person;
struct Person;
Person Person_construct();
Person *Person_print(Person *p);
Person *Person_set_name(Person *p, const char *name_str);
struct Person {
int age;
char name[PERSON_STRMAX];
Person *(*print)(Person *);
Person *(*set_name)(Person *, const char *name_str);
};
static inline Person
Person_default() {
return (Person) {
0,
"",
Person_print,
Person_set_name
};
}
Person.c example
Code:
#include "config.h"
#include "classes/Person.h"
Person
Person_construct()
{
Person p = Person_default();
return p;
}
Person *
Person_print(Person *p)
{
printf("Name: %s\n"
"Age: %d\n", p->name, p->age);
return p;
}
Person *
Person_set_name(Person *p, const char *name_str)
{
strncpy(p->name, name_str, PERSON_STRMAX);
return p;
}
If you want to use it notice you have to pass a pointer to the object for each method call. Also, assigning function pointers is not strictly required. You could just use Person_set_name or Person_print and so on. In fact many C libraries like SDL and APR use this kind of convention.
Code:
Person p = Person_construct();
p.set_name(&p, "Bob");
p.age = 42;
p.print(&p);