Using C to Encapsulate an Abstract Data Type
I used to think that C couldn't be used to create a truly
encapsulated data type. I am very pleased to say that I was wrong. One of
P. J. Plauger's essays showed me how (see References, below) to do it without
incurring any runtime penalty or giving up protoype checking.
Although I've written the example using ISO
C the same technique can be used with K&R, aka traditional, C (see the
Plauger reference for details).
One day I might give a lecture about this technique. In the
meantime, I hope the commented example (below) will help someone else to
understand how to do this.
This document is composed of three units: an example, some references, and
some suggested further reading.
- All of the 7 files below in a single tar archive which has been
encoded with gzip. It's about 4K long.
- The bulk of the encapsulation code is in this file. I made this file
from a bigger one that I use for many projects and left in the static
open_files variable even though it isn't used in the rest of
the example. I think it is instructive.
- Contains the function prototypes and definition of the opaque type.
- I always find myself defining a few types for whatever project I do.
I've taken to putting all those definitions into one file.
- Shows how I work with the out-of-date libraries at UWOCSD (using
prototypes from the man pages), a nifty error reporting function based on
error() from K&R and a driver for the
- Function prototypes for the global functions.
- A program with more than one file needs a makefile, doesn't it?
- A previous version of stream.h that
did not use
const function pointers.
The links here lead to my comments on these books in my list of
recommended technical books.
- Programming on Purpose: essays on software design
- by P. J. Plauger
- published by Prentice-Hall, 1993
- pp. 201-2 (part of Essay 22: Inherit It)
- C Programming FAQs: frequently asked questions
- by Steve Summit
- published by Addison-Wesley, 1996
- `Question 2.4: What's the best way of implementing opaque
(abstract) data types in C?' (p. 32); and
- definition of opaque type (p. 367)
Bobby Schmidt discussed several ways of encapsulation in the
The Learning C/C++urve column of C/C++ User's Journal during 1997. See in particular:
The method I present is discussed in the June column (because I
wrote to Bobby Schmidt about it).
I have a list of various resources for undergraduate computer science
students at UWO.
This document is copyright by its author, J. Blustein. Last modified 19 June 1997 (included references
to Bobby Schmidt's columns). Previous modification 31 July 1996.