Sealed classes and methods: Difference between revisions
→{{header|C}}: Spoke too soon, just figured out an easy way to do this.
(Added C) |
(→{{header|C}}: Spoke too soon, just figured out an easy way to do this.) |
||
Line 27:
It has structs rather than classes which are just a collection of fields. Methods on a struct can be simulated by functions whose first argument is a pointer to the struct.
However, there is no way that the method can tell whether it's receiving a pointer to a 'parent' instance or a pointer to a 'child' field. To use the Wren technique for simulating sealed methods, we therefore need to pass a further parameter, namely a type identifier, as the following code illustrates.
<syntaxhighlight lang="c">#include <stdio.h>
typedef enum {
PARENT,
CHILD
} typeid;
typedef struct {
const char* name;
int age;
} parent;
typedef struct {
parent p;
} child;
void watchMovie(parent *p, typeid id) {
if (id == PARENT) {
printf("%s is watching the movie...\n", p->name);
} else if (id == CHILD) {
if (p->age < 15) {
printf("Sorry, %s, you are too young to watch the movie.\n", p->name);
} else {
printf("%s is watching the movie...\n", p->name);
}
}
}
int main() {
parent p = { "Donald", 42 };
child c1 = { "Lisa", 18 };
child c2 = { "Fred", 10 };
watchMovie(&p, PARENT);
watchMovie(&c1.p, CHILD);
watchMovie(&c2.p, CHILD);
}</syntaxhighlight>
{{out}}
<pre>
Donald is watching the movie...
Lisa is watching the movie...
Sorry, Fred, you are too young to watch the movie.
</pre>
=={{header|FreeBASIC}}==
|