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.
Contents
This document is composed of three units: an example, some references, and
some suggested further reading.
- encapC.tgz
- All of the 7 files below in a single tar archive which has been
encoded with gzip. It's about 4K long.
- stream.c
- 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.
- stream.h
- Contains the function prototypes and definition of the opaque type.
- types.h
- I always find myself defining a few types for whatever project I do.
I've taken to putting all those definitions into one file.
- main.c
- 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 Stream
ADT.
- proto.h
- Function prototypes for the global functions.
- Makefile
- A program with more than one file needs a makefile, doesn't it?
:)
- old-stream.h
- 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.
http://www.csd.uwo.ca/~jamie/C/encapsulatedC.html
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.