Saturday, November 21, 2009

Object-Oriented ANSI C


I used to know that Object Orietned programming is only available with C++/Java but not C. After thinking about it for some time, I found that it could be, I know that for C++/Java guys this doesn't look like Object Oriented programming, but lets give it a try!

The code below uses function pointers to demonstrate "instantiating" a new object, followed by performing "member functions" on the object, and then deleting the object.


/**********************************************************************/
/* */
/* Object Oriented C ! */
/* */
/* Advanced STRUCTURE simulating OO design using function pointers. */
/**********************************************************************/

#include <stdlib.h>

#define delete(a) a->finalize(a)

/**************************/
/* Define a car structure */
/**************************/
typedef struct car_st CAR;
struct car_st {
unsigned int bTurbo:1; /* 1-bit flag */
unsigned int maxSpeed;
unsigned int fuelLevel;
void (*start)();
void (*turbo)();
void (*stop)();
void (*finalize)(struct car_st*);
void (*funcPtrArr[2])();
};

void start()
{
puts("VooVooo");
}

void turbo()
{
puts("Fly baby ... fly");
}

void stop()
{
puts("Race is over baby");
}

/***********************/
/* Simulate distructor */
/***********************/
void finalize( CAR* car )
{
free( car );
}

/**************************/
/* Simualting constructor */
/**************************/
CAR* newCar ()
{
/* Allocating & setting struct elements to Zero */
CAR* newCar = calloc( 1, sizeof(CAR) );

newCar->start = start;
newCar->turbo = turbo;
newCar->stop = stop;
newCar->finalize = finalize;
newCar->funcPtrArr[0] = &start;
newCar->funcPtrArr[1] = &stop;
return newCar;
}

/***********************************************************/
/* Create instances of cars and try to use their functions */
/***********************************************************/
int main (int argc, char* argv[])
{
CAR* dawoo = newCar();
CAR* porsche = newCar();

porsche->bTurbo = 1;

dawoo->start();
dawoo->bTurbo ? dawoo->turbo() : dawoo->stop();
dawoo->funcPtrArr[1]();

porsche->funcPtrArr[0]();
porsche->start();
porsche->bTurbo ? porsche->turbo() : porsche->stop();



delete (porsche);
delete (dawoo);
getchar();
return ( EXIT_SUCCESS );
} /* end main */




The output of this code looks like

VooVooo
Race is over baby
Race is over baby
VooVooo
VooVooo
Fly baby ... fly

1 comments:

Anonymous said...

Cool ;)