Created
December 4, 2022 21:43
-
-
Save nikanos/101e56158436e9d92d1f8c9dc2dc9309 to your computer and use it in GitHub Desktop.
Inheritance example using C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include "Animal.h" | |
void Animal_Ctor(Animal* pa) | |
{ | |
pa->pfspeak=Animal_Speaking; | |
} | |
void Animal_Speaking(Animal* pa) | |
{ | |
puts("Animal Speaking.."); | |
} | |
void Dog_Ctor(Dog* pd,const char* n) | |
{ | |
Animal_Ctor((Animal*)pd); | |
((Animal*)pd)->pfspeak=Dog_Speaking; | |
strcpy(pd->name,n); | |
} | |
void Dog_Speaking(Dog* pd) | |
{ | |
printf("%s says Woof Wood\n",pd->name); | |
} | |
void Cat_Ctor(Cat* pc,const char* n) | |
{ | |
Animal_Ctor((Animal*)pc); | |
((Animal*)pc)->pfspeak=Cat_Speaking; | |
strcpy(pc->name,n); | |
} | |
void Cat_Speaking(Cat* pc) | |
{ | |
printf("%s says Meow Meow\n",pc->name); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef ANIMAL_H | |
#define ANIMAL_H | |
typedef struct Animal | |
{ | |
void (*pfspeak)(); | |
}Animal; | |
void Animal_Ctor(Animal* pa); | |
void Animal_Speaking(Animal* pa); | |
typedef struct Dog | |
{ | |
Animal a; | |
char name[255]; | |
}Dog; | |
void Dog_Ctor(Dog* pd,const char* n); | |
void Dog_Speaking(Dog* pa); | |
typedef struct Cat | |
{ | |
Animal a; | |
char name[255]; | |
}Cat; | |
void Cat_Ctor(Cat* pc,const char* n); | |
void Cat_Speaking(Cat* pc); | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "Animal.h" | |
void MakeAnimalSpeak(Animal* pa) | |
{ | |
pa->pfspeak(pa); | |
} | |
int main() | |
{ | |
Animal a; | |
Dog d; | |
Cat c; | |
Animal_Ctor(&a); | |
Dog_Ctor(&d,"Milo"); | |
Cat_Ctor(&c,"Kitty"); | |
MakeAnimalSpeak(&a); | |
MakeAnimalSpeak((Animal*)&d); | |
MakeAnimalSpeak((Animal*)&c); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment