PDA

View Full Version : C "classes"



danbaron
29-07-2011, 00:20
Here is my (probably primitive) way of imitating classes and object creation/destruction in C.

:idea: :?:


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

//-------------------------------------------------------------------------------------------------------------

// Use a struct to function as the data part of the class.

struct Astruct
{
int N[10];
bool B;
};

// Make a function to return a new instance of the struct.

struct Astruct* newAstruct(void)
{
return malloc(sizeof(struct Astruct));
}

// Make functions which take the struct as a parameter.

void AstructSetN(struct Astruct* as, int index, int value)
{
as->N[index] = value;
}

int AstructGetN(struct Astruct* as, int index)
{
return as->N[index];
}

void AstructSetB(struct Astruct* as, bool value)
{
as->B = value;
}

bool AstructGetB(struct Astruct* as)
{
return as->B;
}

//-------------------------------------------------------------------------------------------------------------

int main(int argc, char *argv[])
{
struct Astruct* A;
int Nval;
bool Bval;
char c;

A = newAstruct();

AstructSetN(A, 4, 6);
AstructSetB(A, true);
Nval = AstructGetN(A, 4);
Bval = AstructGetB(A);

printf("Nval = %u\n", Nval);
printf("Bval = %u\n\n", Bval);

free(A);

struct Astruct* C;
C = newAstruct();

AstructSetN(C, 7, 3);
AstructSetB(C, false);
Nval = AstructGetN(C, 7);
Bval = AstructGetB(C);

printf("Nval = %u\n", Nval);
printf("Bval = %u\n\n", Bval);

c = getchar();

return 0;
}

Petr Schreiber
29-07-2011, 08:57
Hi Dan,

it might look primitive, but it is quite usable way, I use the same approach in ThinBASIC.


Petr

danbaron
29-07-2011, 09:36
Or Petr, maybe we're both primitive.

:p

Petr Schreiber
29-07-2011, 10:15
Warner Bros proudly presents: "The Primitives"
Starring Dan Baron and Petr Schreiber in shocking view on programming world.

Coming to your theaters in Q1 2012!

danbaron
30-07-2011, 05:59
You can't escape, and there's nowhere to hide!

7358