💾 Archived View for koyu.space › aartaka › public › assets › oop-c-primer-cleanup.c captured on 2024-05-10 at 11:07:19.

View Raw

More Information

-=-=-=-=-=-=-

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define class struct

typedef class animal {
        char *name;
        char *species;
} Animal;

void animal_eats (Animal *self)
{
        printf("%s eats ???\n", self->name);
}

char *animal_get_name (Animal *self)
{
        return self->name;
}
void animal_set_name (Animal *self, char *name)
{
        self->name = name;
}

typedef class bird {
        Animal parent;
} Bird;

void bird_eats (Bird *self)
{
        printf("%s eats worms\n", animal_get_name(self));
}

typedef class carnivoire {
        Animal parent;
} Carnivoire;

void carnivoire_eats (Carnivoire *self)
{
        printf("%s eats meat (a shame—it involves killing other animals)\n",
               animal_get_name(self));
}

typedef class feline {
        Carnivoire parent;
        bool claws_out;
} Feline;

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),                      \
                 Bird *: bird_eats,             \
                 Carnivoire *: carnivoire_eats, \
                 Cat *: cat_eats,               \
                 default: animal_eats)          \
                ((animal))

int main (void)
{
        Animal oldie = {.name = "Oldie", .species = "Miacid"};
        printf("This really old animal is %s of %s species\n", oldie.name, oldie.species);

        Bird woodie = {{.name = "Woodie", .species = "Dryocopus pileatus"}};
        eats(&woodie);

        Carnivoire sabre_tooth = {{.name = "Diego", .species = "Dinictis"}};
        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;
}