Tiny BASIC

Interpreter and Compiler Project

Object-oriented Programming in C?

Thursday, 24th October 2019

Yes, this blog post about C does concern Tiny BASIC - see later.

Despite C not being an object-oriented (OO) language, it's possible to write OO programs in it - within certain limits. C allows you to create pointers to functions, to point them at various functions and call those functions that way. It also allows you to put those function pointers in a structure. So functions that act upon a structure can be put in that structure alongside the existing data, the whole becoming properties and methods.

/* thing.h */
typedef string thing Thing; typedef struct thing { int data; void (*action) (Thing *thing); } Thing;

There's a bit more to do than in a "real" OO language, and some differences. Your constructor has to initialise the methods as well as the properties. And because methods have to be initialised by the constructor, the constructor can't be one of them. A constructor for Thing might look like this:

/* thing.c */
#include "thing.h"
static void action (Thing *thing) {
  /* perform some action on thing */
}
Thing *new_Thing (void) {
  Thing *this;
  this = malloc (sizeof (Thing));
  this->action = action;
  this->data = 0;
}

There is a bit of a clumsy syntax. The functions like action() cannot "know" that they're called through that pointer, nor if there are multiple instances of that object can they know with which one they were called. So you need to pass the object through as a parameter, sometimes meaning that it is repeated in the call:

a_thing = new_Thing ();
a_thing->action (a_thing);

There's more to this. You can make data protected or private in various ways. Limited polymorphism is possible by pointing any of the methods' function pointers to different functions, although adding new methods or properties to a subclass becomes very tedious and possibly not worth it from a readability point of view.

In Tiny BASIC, the C generation code was written this way. The intention is to gradually refactor the whole project into this form. This will make it easier to support variants of Tiny BASIC. If the parser, interpreter and C generation modules becomes objects, then methods like parse_print_statement() can be overridden to support the functionality offered in extended Tiny BASICs.

Comments

New Comment

Yes No