💾 Archived View for koyu.space › aartaka › public › assets › oop-c-primer-original.c captured on 2024-06-16 at 12:36:00.
⬅️ Previous capture (2024-05-10)
-=-=-=-=-=-=-
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> struct animal { char *name; char *species; }; #define class struct typedef class animal Animal; typedef class carnivoire { Animal parent; } Carnivoire; void animal_eats (Animal *self) { printf("%s eats ???\n", self->name); } void carnivoire_eats (Carnivoire *self) { printf("%s eats meat (a shame—it involves killing other animals)\n", self->parent.name); } char *animal_get_name (Animal *self) { return self->name; } void animal_set_name (Animal *self, char *name) { self->name = name; } typedef class feline { Carnivoire parent; bool claws_out; } Feline; // Don't have to define name getter/setter: animal has it already. bool feline_get_claws_out (Feline *self) { return self->claws_out; } void feline_protract_claws (Feline *self) { self->claws_out = true; } void feline_retract_claws (Feline *self) { self->claws_out = false; } typedef class cat { Feline parent; } Cat; void cat_purr (Cat *self) { printf("%s purrs...\n", animal_get_name(self)); feline_retract_claws(self); } void cat_eats (Cat *self) { printf("%s eats mice\n", animal_get_name(self)); } #define eats(animal) \ _Generic((animal), \ Carnivoire *: carnivoire_eats, \ Cat *: cat_eats, \ default: animal_eats) \ ((animal)) int main (void) { struct animal oldie = {.name = "Oldie", .species = "Miacid"}; printf("This really old animal is %s of %s species\n", oldie.name, oldie.species); Carnivoire sabre_tooth = {{.name = "Diego", .species = "Dinictis"}}; eats((Animal *)&sabre_tooth); eats(&sabre_tooth); // My little sweet boy Cat Kalyam = {{{{.name = "Kalyam", .species = "Felis catus"}}, .claws_out = true}}; printf("%s's claws are %stracted\n", animal_get_name(&Kalyam), (feline_get_claws_out(&Kalyam) ? "pro" : "re")); eats(&Kalyam); cat_purr(&Kalyam); printf("%s's claws are %stracted\n", animal_get_name(&Kalyam), (feline_get_claws_out(&Kalyam) ? "pro" : "re")); return EXIT_SUCCESS; }