Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct foo {
- void (*print)(struct foo *, FILE *);
- };
- void
- print_foo(struct foo *obj, FILE *f)
- {
- obj->print(obj, f);
- }
- struct bar {
- struct foo vtable;
- int n;
- };
- void print_bar(struct foo *obj, FILE *f)
- {
- struct bar *b = (struct bar *)obj;
- fprintf(f, "bar: %d\n", b->n);
- }
- struct foo *
- make_bar(int n) {
- struct bar *b;
- b = malloc(sizeof *b);
- b->vtable.print = print_bar;
- b->n = n;
- return (struct foo *)b;
- }
- struct baz {
- struct foo vtable;
- double d;
- };
- void print_baz(struct foo *obj, FILE *f)
- {
- struct baz *b = (struct baz *)obj;
- fprintf(f, "baz: %f\n", b->d);
- }
- struct foo *
- make_baz(double d) {
- struct baz *b;
- b = malloc(sizeof *b);
- b->vtable.print = print_baz;
- b->d = d;
- return (struct foo *)b;
- }
- int
- main(void)
- {
- struct foo *objects[2];
- objects[0] = make_bar(1);
- objects[1] = make_baz(2.0);
- print_foo(objects[0], stdout);
- print_foo(objects[1], stdout);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement