Skip to content

Instantly share code, notes, and snippets.

@ibeauregard
Last active April 2, 2021 15:02
Show Gist options
  • Save ibeauregard/67605af61ffe573dbb31c337bf33cd91 to your computer and use it in GitHub Desktop.
Save ibeauregard/67605af61ffe573dbb31c337bf33cd91 to your computer and use it in GitHub Desktop.
Demonstration of dot notation and encapsulation in C
/* char_map.h */
#ifndef CHAR_MAP_H
#define CHAR_MAP_H
typedef struct char_map CharMap;
struct char_map {
char wall;
char corridor;
char path;
char entrance;
char exit;
void (*print)(CharMap* self);
void (*delete)(CharMap* self);
};
extern const struct char_map_class {
CharMap* (*new)();
} CharMapClass;
#endif
/* char_map.c */
#include "char_map.h"
#include <stdlib.h>
#include <stdio.h>
static CharMap* new();
const struct char_map_class CharMapClass = {
.new = &new
};
static void print(CharMap* self);
static void delete(CharMap* self);
CharMap* new()
{
CharMap* self = malloc(sizeof (CharMap));
self->print = &print;
self->delete = &delete;
return self;
}
void print(CharMap* self)
{
printf("%c%c%c%c%c",
self->wall, self->corridor, self->path, self->entrance, self->exit);
}
void delete(CharMap* self)
{
free(self);
}
/* main.c */
#include "char_map.h"
int main()
{
CharMap* map = CharMapClass.new();
map->print(map);
map->delete(map);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment