Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*-
- * Copyright (c) 2012 valsorym <[email protected]>.
- * All rights reserved.
- *
- * Discussion on the forums.freebsd.org.
- * url: http://forums.freebsd.org/showthread.php?p=177208
- */
- /*
- * Very simple class, for example OOD in ANSI C.
- */
- #ifndef HUMAN_H
- #define HUMAN_H
- #include <string.h>
- #include <stdlib.h>
- #include "objectmode.h"
- /* NEW TYPES */
- /* ************************************************************************* */
- /*
- * Class has information only human age and it name.
- * For security, we use the methods of initialization parameters.
- */
- typedef struct {
- w_class *class; /* class description */
- int age;
- char *name;
- int (*set_age)(void *, int );
- char *(*set_name)(void *, char *);
- } w_human;
- /* INTERFACE */
- /* ************************************************************************* */
- static int set_age(void *, int );
- static char *set_name(void *, char *);
- /* IMPLEMENTATION */
- /* ************************************************************************* */
- /* Constructor and Destructor realisation. */
- static void
- *create(void *self, va_list *app)
- {
- w_class *c = (w_class *)self;
- w_human *p = (w_human *)malloc(c->size);
- if (p) {
- p->class = c;
- p->set_age = set_age;
- p->set_name = set_name;
- p->set_age(p, (int)va_arg(*app, const int));
- p->set_name(p, (char *)va_arg(*app, const char *));
- }
- return p;
- }
- static void
- *destroy(void *self)
- {
- w_human *p = (w_human *)self;
- free(p);
- return self;
- }
- /*
- * Change/Set age of human.
- */
- static int
- set_age(void *self, int age)
- {
- w_human *p = (w_human *)self;
- if (age < 0 || age > 110)
- age = 0;
- if (self && p->set_age) {
- p->age = age;
- return 1;
- }
- return 0;
- }
- /*
- * Change/Set name of human.
- * Returns a new name.
- */
- static char
- *set_name(void *self, char *name) {
- w_human *p = (w_human *)self;
- if (self && p->set_name) {
- free(p->name);
- p->name = (char *)malloc((strlen(name)+1)*sizeof(char));
- if (p->name == NULL)
- return NULL;
- strcpy(p->name, name);
- return p->name;
- }
- return NULL;
- }
- /* The point of initialization. */
- static w_class _human = {
- sizeof(w_human), create, destroy
- };
- w_class *i_human = &_human;
- #endif
- /* The End. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement