Skip to content

Instantly share code, notes, and snippets.

@psilord
Last active September 13, 2023 22:21
Show Gist options
  • Select an option

  • Save psilord/841dbd9d823deb7f9fddf1226dbf63ea to your computer and use it in GitHub Desktop.

Select an option

Save psilord/841dbd9d823deb7f9fddf1226dbf63ea to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct person person;
struct person
{
/* The data fields */
char *first_name;
char *last_name;
int age;
/* The methods. */
void (*set_first_name)(person *, char *);
char* (*get_first_name)(person *);
void (*set_last_name)(person *, char *);
char* (*get_last_name)(person *);
void (*set_age)(person *, int);
int (*get_age)(person *);
};
/* The variable 'o' in these functions is in effect 'this' in C++ or also
'self' in python. Single DIspatch only, in this context.
*/
void set_first_name(person *o, char *val)
{
if (o->first_name != NULL) {
free(o->first_name);
}
o->first_name = strdup(val);
}
char* get_first_name(person *o) { return o->first_name; }
void set_last_name(person *o, char *val)
{
if (o->last_name != NULL) {
free(o->last_name);
}
o->last_name = strdup(val);
}
char* get_last_name(person *o) { return o->last_name; }
void set_age(person *o, int val) { o->age = val; }
int get_age(person *o) { return o->age; }
/* person constructor */
person* make_person(char *first_name, char *last_name, int age)
{
person *o = (person*)malloc(sizeof(person) * 1);
if (o == NULL) {
printf("Out of memory!\n");
exit(EXIT_FAILURE);
}
/* fundamental field initialization to valid values. */
o->first_name = NULL;
o->last_name = NULL;
o->age = 0;
/* connect the methods into the instance*/
o->set_first_name = set_first_name;
o->get_first_name = get_first_name;
o->set_last_name = set_last_name;
o->get_last_name = get_last_name;
o->set_age = set_age;
o->get_age = get_age;
/* Now initalize the instance with the method functions and constructor values. */
o->set_first_name(o, first_name);
o->set_last_name(o, last_name);
o->set_age(o, age);
return o;
}
void free_person(person *o)
{
if (o != NULL) {
free(o->first_name);
free(o->last_name);
}
free(o);
}
int main(void)
{
person *p0, *p1;
p0 = make_person("Fred", "Baily", 44);
p1 = make_person("Jane", "Smith", 45);
printf("The first person is:\n");
printf(" First Name: %s\n", p0->get_first_name(p0));
printf(" Last Name: %s\n", p0->get_last_name(p0));
printf(" Age: %d\n", p0->get_age(p0));
printf("The second person is:\n");
printf(" First Name: %s\n", p1->get_first_name(p1));
printf(" Last Name: %s\n", p1->get_last_name(p1));
printf(" Age: %d\n", p1->get_age(p1));
free_person(p0);
free_person(p1);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment