polymorphism simulation in plain C with a simple structures
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {aDog, aCat} CLASS;
typedef void speak_();
typedef struct Animal
{
int id;
void (*speak)();
}ANIMAL;
typedef struct Dog
{
int id;
void (*speak)();
char* name;
int tagId;
}DOG;
typedef struct Cat
{
int id;
void (*speak)();
char* name;
}CAT;
void bark(){printf("whoa! ");}
void meow(){printf("meow! ");}
ANIMAL* ctor(CLASS class)
{
ANIMAL* animal = (ANIMAL*)malloc(sizeof(ANIMAL));
animal->speak = 0;
if(aDog==class) animal->speak = bark;
if(aCat==class) animal->speak = meow;
return animal;
}
void dtor(ANIMAL* animal)
{
if(animal) free(animal); animal = 0;
}
typedef struct Shelter
{
ANIMAL** animals;
int animalCount;
}SHELTER;
void includeAnimal(SHELTER* shelter, ANIMAL* animal)
{
int i;
for(i=0; i<shelter->animalCount; i++)
{
if(animal==shelter->animals[i]) return;
}
shelter->animalCount++;
shelter->animals = (ANIMAL**)realloc(shelter->animals, sizeof(ANIMAL*)*shelter->animalCount);
shelter->animals[shelter->animalCount-1] = animal;
}
void excludeAnimal(SHELTER* shelter, ANIMAL* animal)
{
int i;
int j;
for(i=0; i<shelter->animalCount; i++)
{
if(animal==shelter->animals[i])
{
shelter->animalCount--;
for(j=i; j<shelter->animalCount; j++)
{
shelter->animals[i] = shelter->animals[i+1];
}
shelter->animals = (ANIMAL**)realloc(shelter->animals, sizeof(ANIMAL*)*shelter->animalCount);
break;
}
}
}
int main(void)
{
int i;
printf("Hello World!\n");
SHELTER* shelter = (SHELTER*)malloc(sizeof(SHELTER));
shelter->animals = (ANIMAL**)0;
shelter->animalCount = 0;
ANIMAL* myPet = (DOG*)ctor(aDog);
printf("my pet says: "); myPet->speak(); printf("\n");
dtor(myPet);
myPet = (CAT*)ctor(aCat);
printf("my pet says: "); myPet->speak(); printf("\n");
DOG* yourDog = (DOG*)ctor(aDog);
DOG* hisDog = (DOG*)ctor(aDog);
CAT* hersCat = (CAT*)ctor(aCat);
includeAnimal(shelter, myPet);
includeAnimal(shelter, yourDog);
includeAnimal(shelter, hisDog);
includeAnimal(shelter, hersCat);
printf("\n____________\n");
for(i=0; i<shelter->animalCount; i++)
shelter->animals[i]->speak();
printf("\n____________\n");
excludeAnimal(shelter, hisDog);
excludeAnimal(shelter, hersCat);
printf("\n____________\n");
for(i=0; i<shelter->animalCount; i++)
shelter->animals[i]->speak();
printf("\n____________\n");
dtor(hersCat);
dtor(hisDog);
dtor(yourDog);
free(shelter);
printf("Game Over!\n");
return 0;
}
|
run
| edit
| history
| help
|
1
|
|
|