Sealed classes and methods: Difference between revisions
Content deleted Content added
Added C |
→{{header|C}}: Spoke too soon, just figured out an easy way to do this. |
||
Line 27: | 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. |
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. |
||
To simulate inheritance, one can embed a 'parent' field ''first'' in the 'child' struct and then pass the address of that field to 'parent' methods. |
|||
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. |
|||
So, for the purposes of this task, we can say that structs and simulated methods in C are by their nature always sealed. |
|||
<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}}== |
=={{header|FreeBASIC}}== |