2010年8月20日 星期五

[C] OOP in C sample

Because I got a job, it was a C project.
So I am learning how to implement OOP in C now.
This is a example searched form google.
I use Xcode 3.2.3 with gcc4.2 to implement and test it.


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

typedef void (*Walk_Fun)(struct Animal *a_This);
typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);

typedef struct _Animal_Vtable{
Walk_Fun Walk;
Dtor_Fun Dtor;
}Animal_Vtable;

typedef struct _Animal{
Animal_Vtable vtable;

char *Name;
}Animal;

typedef struct _Dog{
Animal_Vtable vtable;

char *Name; // mirror member variables for easy access
char *Type;
}Dog;

void Animal_Walk(Animal *a_This){
printf("Animal (%s) walking\n", a_This->Name);
}

struct Animal* Animal_Dtor(struct Animal *a_This){
printf("animal::dtor\n");
return a_This;
}

Animal *Animal_Alloc(){
return (Animal*)malloc(sizeof(Animal));
}

Animal *Animal_New(Animal *a_Animal){
a_Animal->vtable.Walk = Animal_Walk;
a_Animal->vtable.Dtor = Animal_Dtor;
a_Animal->Name = "Anonymous";
return a_Animal;
}

void Animal_Free(Animal *a_This){
a_This->vtable.Dtor(a_This);

free(a_This);
}

void Dog_Walk(Dog *a_This){
printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}

Dog* Dog_Dtor(Dog *a_This){
// explicit call to parent destructor
Animal_Dtor((Animal*)a_This);

printf("dog::dtor\n");

return a_This;
}

Dog *Dog_Alloc(){
return (Dog*)malloc(sizeof(Dog));
}

Dog *Dog_New(Dog *a_Dog){
// explict call to parent constructor
Animal_New((Animal*)a_Dog);

a_Dog->Type = "Dog type";
a_Dog->vtable.Walk = (Walk_Fun) Dog_Walk;
a_Dog->vtable.Dtor = (Dtor_Fun) Dog_Dtor;

return a_Dog;
}


int main (int argc, const char * argv[]) {
/*
base class:
Animal *a_Animal = Animal_New(Animal_Alloc());
*/
Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());

a_Animal->vtable.Walk(a_Animal);

Animal_Free(a_Animal);

return 0;
}

沒有留言:

張貼留言

Hello