Skip to content

Instantly share code, notes, and snippets.

@hosaka
Created August 10, 2015 16:28
Show Gist options
  • Save hosaka/538408edc03326b40596 to your computer and use it in GitHub Desktop.
Save hosaka/538408edc03326b40596 to your computer and use it in GitHub Desktop.
Basic inheritance using structs in C
#include <stdio.h>
#include <stdlib.h>
// super "class"
typedef struct
{
int age;
double weight;
} Animal;
// sub "class"
typedef struct
{
Animal super;
double wingspan;
} Bird;
// an init method (a constructor) can set up the objects
void new_Animal (Animal *self, int age, double weight)
{
self->age = age;
self->weight = weight;
}
// a subclass init
void new_Bird (Bird *self, int age, double weight, double wingspan)
{
// in order to access the super class we typecast the bird pointer to Animal
// and call the animal init function
new_Animal( (Animal *) self, age, weight );
// set additional fields relevant to our subclass
self->wingspan = wingspan;
}
// different functions that access the objects need to chain the calls to the
// superclass equivalent functions first, before doing subclass specifics
void print_animal(const Animal *self)
{
printf("animal: %d age, weights %.2fkg\n", self->age, self->weight);
}
void print_bird(const Bird *self)
{
// again cast to treat it like Animal class
print_animal( (Animal *) self );
printf("wingspan: %.2f\n", self->wingspan);
}
int main(int argc, char const *argv[])
{
// since the Bird's first element is a superclass Animal and the have
// the same memory address, we can cast the Bird to an animal
// the addresses are the same, of course lol
Bird b;
printf("%p\n", &b);
printf("%p\n", &b.super);
// running subclass specific function will chain call the superclass
// init and print functions
new_Bird(&b, 10, 43, 2);
print_bird(&b);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment