Last active
December 22, 2015 08:08
-
-
Save brookskindle/6442526 to your computer and use it in GitHub Desktop.
class like structures in 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> | |
//define a struct to contain variables and function pointers, much like a class | |
typedef struct ex { | |
//declare some variables | |
int x; | |
//declare some methods (aka, function pointers) | |
void (*const p)(void); //let p be a constant pointer | |
void (*const setX)(struct ex *, int); //must pass self-referential pointer to imitate class scope | |
int (*const getX)(const struct ex *); | |
} ExClass; | |
//function prototypes | |
ExClass initialize(); //like a constructor | |
void print(void); | |
void setX(ExClass *, int); | |
int getX(const ExClass *); | |
//function definitions | |
ExClass initialize() { | |
ExClass c = {0, print, setX, getX}; | |
return c; | |
} | |
void print(void) { | |
printf("Just a generic print statement\n"); | |
} | |
void setX(ExClass *this, int v) { | |
this->x = v; | |
} | |
int getX(const ExClass *this) { | |
return this->x; | |
} | |
int main(void) { | |
ExClass e = initialize(); //call constructor | |
e.setX(&e, 100); | |
e.p(); | |
printf("Value of e.x = %d\n", e.getX(&e)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment