Home

Sep 17, 2015

Article: Abstract data types in C


Untitled document Using opaque pointers, true abstract data types can be implemented in C.
Category: General
Posted by: hamren
Untitled document

An opaque pointer is a pointer that points to a data structure, usually a struct, whose definition is not visible outside the implementing module.

Lets implement a counter with an initial value and an upper limit.We need:

  • A type declaration for the abstract type
  • A "constructor" function, i.e. a function that crreates an instance of the abstract type.
  • A "destructor" function, i.e. a function that deletes an instance.
  • A function to increment the value.
  • A function to read the value.

This is what the header file could look like.

string(90) "Smarty error: unable to read resource: "/h/www/sdu/cmsms/src/c/abstract/parts/counter.h.1""

Note that there is no definition of _Counter, just a declaration, i.e. we say that it exists, but not what it looks like. This is what guarantees that it is, and will remain, an abstract type.

By local convention, each "member function" is prefixed by a lower-cased class name and two underscores.

Before we start on the implementation, we need a few definitions:

string(100) "Smarty error: unable to read resource: "/h/www/sdu/cmsms/src/c/abstract/parts/counter.c.definitions""

As Counters definition is hidden, the only way to create and delete instances is by using constructors and destructors:

string(100) "Smarty error: unable to read resource: "/h/www/sdu/cmsms/src/c/abstract/parts/counter.c.constructor""

The actual work is done by:

string(93) "Smarty error: unable to read resource: "/h/www/sdu/cmsms/src/c/abstract/parts/counter.c.meat""

A short test program:

string(93) "Smarty error: unable to read resource: "/h/www/sdu/cmsms/src/c/abstract/parts/counter.c.main""