ZetCode

Modula-2 opaque types

last modified November 26, 2026 Modula-2

The fraction module at the end of the modules article exports its record type, so any program can store a fraction with a zero denominator. An opaque type solves this: the definition module names the type but does not describe it, and only the implementation module knows its structure. Clients can hold values of the type and pass them to the module's procedures, nothing more. A type used this way is called an abstract data type.

An opaque type

In the definition module an opaque type is declared by its name alone, with no = and no type after it.

Fractions.def
DEFINITION MODULE Fractions;

TYPE
  Fraction;

PROCEDURE Make(n, d: INTEGER): Fraction;
PROCEDURE Write(f: Fraction);
PROCEDURE Free(VAR f: Fraction);

END Fractions.

TYPE Fraction; tells clients that the type exists. The procedures create a fraction, print it and free it; a client has no other way to work with one.

Fractions.mod
IMPLEMENTATION MODULE Fractions;
FROM InOut IMPORT WriteString, WriteInt;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;

TYPE
  Fraction = POINTER TO FractionRec;
  FractionRec = RECORD
    num, den: INTEGER
  END;

PROCEDURE Make(n, d: INTEGER): Fraction;
VAR
  f: Fraction;
BEGIN
  NEW(f);
  f^.num := n;
  f^.den := d;
  RETURN f
END Make;

PROCEDURE Write(f: Fraction);
BEGIN
  WriteInt(f^.num, 0); WriteString("/"); WriteInt(f^.den, 0)
END Write;

PROCEDURE Free(VAR f: Fraction);
BEGIN
  DISPOSE(f)
END Free;

END Fractions.

The implementation module completes the declaration: a Fraction is a pointer to a record of two integers. Make is the constructor: it allocates the record with NEW, as in the pointers article, and returns the pointer. Free is the destructor.

half.mod
MODULE half;
FROM InOut IMPORT WriteString, WriteLn;
FROM Fractions IMPORT Fraction, Make, Write, Free;

VAR
  f: Fraction;

BEGIN
  f := Make(1, 2);
  WriteString("f = "); Write(f); WriteLn;
  Free(f)
END half.

The client declares a variable of type Fraction and uses it only through the procedures. It never sees the pointer or the record.

$ gm2 -c Fractions.mod
$ gm2 half.mod Fractions.o -o half
$ ./half
f = 1/2

The fields are hidden

Because the definition module does not describe the type, a client cannot reach the fields. The next program tries to set the denominator directly.

fields.mod
MODULE fields;
FROM InOut IMPORT WriteLn;
FROM Fractions IMPORT Fraction, Make, Write;

VAR
  f: Fraction;

BEGIN
  f := Make(1, 2);
  f^.den := 0;
  Write(f); WriteLn
END fields.

The compiler refuses to dereference a value of an opaque type from another module. The client is compiled with -c here. GNU Modula-2 (13 and 15.2) misses the error in the one-step command gm2 fields.mod Fractions.o -o fields when Fractions.mod lies in the same directory: to build the start-up code the compiler then reads the implementation module, and the hidden structure leaks into the client. With only the definition module in reach, the one-step build rejects the program too.

$ gm2 -c fields.mod
fields.mod:10:4: error: In program module ‘fields’: ‘f’ is declared with an opaque type from a different module and cannot be dereferenced
   10 |   f^.den := 0;
      |    ^
fields.mod:10:3: error: the type of ‘bad opaque pointer dereference’ is not a record (but ‘ADDRESS’) and therefore it has no field
   10 |   f^.den := 0;
      |   ^~

Opaque types are pointers

Wirth's Modula-2 requires the full type behind an opaque type to be a pointer. The compiler of a client then knows the size of the type, 8 bytes, without knowing what it points to. The next module tries to use a cardinal instead.

Ids.def
DEFINITION MODULE Ids;

TYPE
  Id;

PROCEDURE NewId(): Id;

END Ids.

Ids hands out identifiers of the opaque type Id.

Ids.mod
IMPLEMENTATION MODULE Ids;

TYPE
  Id = CARDINAL;

VAR
  last: Id;

PROCEDURE NewId(): Id;
BEGIN
  INC(last);
  RETURN last
END NewId;

BEGIN
  last := 0
END Ids.

The implementation declares Id as CARDINAL. gm2 rejects this; the first line of the message names an unrelated module, but the second gives the reason. The -fextended-opaque option, a GNU extension, lifts the restriction; portable code declares the type as a pointer.

$ gm2 -c Ids.mod
cc1gm2: error: In definition module ‘COROUTINES’: opaque type (Id) should be equivalent to a POINTER or an ADDRESS
Ids.mod:4:3: error: if you really need a non POINTER type use the -fextended-opaque switch
    4 |   Id = CARDINAL;
      |   ^~

Reading the parts

Now that clients cannot touch the fields, the module decides what a fraction looks like. The second version keeps every fraction reduced, with the sign in the numerator, and lets clients read the two parts.

Fractions.def
DEFINITION MODULE Fractions;

TYPE
  Fraction;

PROCEDURE Make(n, d: INTEGER): Fraction;
PROCEDURE Num(f: Fraction): INTEGER;
PROCEDURE Den(f: Fraction): INTEGER;
PROCEDURE Write(f: Fraction);
PROCEDURE Free(VAR f: Fraction);

END Fractions.

Num and Den give read access to the parts of a fraction. There are no procedures that change them, so a fraction cannot be modified after it is made.

Fractions.mod
IMPLEMENTATION MODULE Fractions;
FROM InOut IMPORT WriteString, WriteInt;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;

TYPE
  Fraction = POINTER TO FractionRec;
  FractionRec = RECORD
    num, den: INTEGER
  END;

PROCEDURE Gcd(a, b: INTEGER): INTEGER;
VAR
  t: INTEGER;
BEGIN
  a := ABS(a); b := ABS(b);
  WHILE b # 0 DO
    t := a MOD b; a := b; b := t
  END;
  RETURN a
END Gcd;

PROCEDURE Make(n, d: INTEGER): Fraction;
VAR
  f: Fraction;
  g: INTEGER;
BEGIN
  IF d < 0 THEN n := -n; d := -d END;
  g := Gcd(n, d);
  NEW(f);
  f^.num := n DIV g;
  f^.den := d DIV g;
  RETURN f
END Make;

PROCEDURE Num(f: Fraction): INTEGER;
BEGIN
  RETURN f^.num
END Num;

PROCEDURE Den(f: Fraction): INTEGER;
BEGIN
  RETURN f^.den
END Den;

PROCEDURE Write(f: Fraction);
BEGIN
  WriteInt(f^.num, 0); WriteString("/"); WriteInt(f^.den, 0)
END Write;

PROCEDURE Free(VAR f: Fraction);
BEGIN
  DISPOSE(f)
END Free;

END Fractions.

Make moves a negative sign from the denominator to the numerator and divides both parts by their greatest common divisor. Gcd is not in the definition module, so it stays private to the implementation.

parts.mod
MODULE parts;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Fractions IMPORT Fraction, Make, Num, Den, Write, Free;

VAR
  a, b: Fraction;

PROCEDURE Show(f: Fraction);
BEGIN
  Write(f);
  WriteString(": numerator "); WriteInt(Num(f), 0);
  WriteString(", denominator "); WriteInt(Den(f), 0); WriteLn
END Show;

BEGIN
  a := Make(6, -8);
  b := Make(0, 5);
  Show(a);
  Show(b);
  Free(a);
  Free(b)
END parts.

6/-8 is stored as -3/4 and 0/5 as 0/1, so equal values always have equal parts. The client reads them with Num and Den; it could not change them even if it tried.

$ gm2 -c Fractions.mod
$ gm2 parts.mod Fractions.o -o parts
$ ./parts
-3/4: numerator -3, denominator 4
0/1: numerator 0, denominator 1

Rejecting invalid values

The third version refuses to create a fraction with a zero denominator and counts the fractions that exist, which helps to find values that were never freed.

Fractions.def
DEFINITION MODULE Fractions;

TYPE
  Fraction;

PROCEDURE Make(n, d: INTEGER): Fraction;
PROCEDURE Num(f: Fraction): INTEGER;
PROCEDURE Den(f: Fraction): INTEGER;
PROCEDURE Write(f: Fraction);
PROCEDURE Free(VAR f: Fraction);
PROCEDURE Live(): CARDINAL;

END Fractions.

Live returns the number of fractions that have been made and not yet freed.

Fractions.mod
IMPLEMENTATION MODULE Fractions;
FROM InOut IMPORT WriteString, WriteInt;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;

TYPE
  Fraction = POINTER TO FractionRec;
  FractionRec = RECORD
    num, den: INTEGER
  END;

VAR
  live: CARDINAL;

PROCEDURE Gcd(a, b: INTEGER): INTEGER;
VAR
  t: INTEGER;
BEGIN
  a := ABS(a); b := ABS(b);
  WHILE b # 0 DO
    t := a MOD b; a := b; b := t
  END;
  RETURN a
END Gcd;

PROCEDURE Make(n, d: INTEGER): Fraction;
VAR
  f: Fraction;
  g: INTEGER;
BEGIN
  IF d = 0 THEN RETURN NIL END;
  IF d < 0 THEN n := -n; d := -d END;
  g := Gcd(n, d);
  NEW(f);
  f^.num := n DIV g;
  f^.den := d DIV g;
  INC(live);
  RETURN f
END Make;

PROCEDURE Num(f: Fraction): INTEGER;
BEGIN
  RETURN f^.num
END Num;

PROCEDURE Den(f: Fraction): INTEGER;
BEGIN
  RETURN f^.den
END Den;

PROCEDURE Write(f: Fraction);
BEGIN
  IF f = NIL THEN
    WriteString("undefined")
  ELSE
    WriteInt(f^.num, 0); WriteString("/"); WriteInt(f^.den, 0)
  END
END Write;

PROCEDURE Free(VAR f: Fraction);
BEGIN
  IF f # NIL THEN
    DISPOSE(f);
    DEC(live)
  END
END Free;

PROCEDURE Live(): CARDINAL;
BEGIN
  RETURN live
END Live;

BEGIN
  live := 0
END Fractions.

Make returns NIL for a zero denominator, so an invalid fraction is never created; otherwise it counts the new fraction. Write and Free accept NIL, and Free lowers the count. The variable live is hidden module state, initialised in the module body.

valid.mod
MODULE valid;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Fractions IMPORT Fraction, Make, Write, Free, Live;

VAR
  a, b: Fraction;

BEGIN
  a := Make(3, 4);
  b := Make(5, 0);
  WriteString("a = "); Write(a); WriteLn;
  WriteString("b = "); Write(b); WriteLn;
  IF b = NIL THEN
    WriteString("b was rejected"); WriteLn
  END;
  WriteString("live fractions: "); WriteCard(Live(), 0); WriteLn;
  Free(a);
  Free(b);
  WriteString("live fractions: "); WriteCard(Live(), 0); WriteLn
END valid.

5/0 comes back as NIL. A client may compare a value of an opaque type with NIL, because the type is a pointer. Only a was allocated, so one fraction is live until it is freed.

$ gm2 -c Fractions.mod
$ gm2 valid.mod Fractions.o -o valid
$ ./valid
a = 3/4
b = undefined
b was rejected
live fractions: 1
live fractions: 0

Building on the interface

New operations do not have to go into Fractions. Another module can build them from the exported procedures alone.

FracMath.def
DEFINITION MODULE FracMath;
FROM Fractions IMPORT Fraction;

PROCEDURE Add(a, b: Fraction): Fraction;
PROCEDURE Mul(a, b: Fraction): Fraction;
PROCEDURE Equal(a, b: Fraction): BOOLEAN;

END FracMath.

The definition module of FracMath imports the opaque type, so its procedures can take and return fractions.

FracMath.mod
IMPLEMENTATION MODULE FracMath;
FROM Fractions IMPORT Fraction, Make, Num, Den;

PROCEDURE Add(a, b: Fraction): Fraction;
BEGIN
  RETURN Make(Num(a) * Den(b) + Num(b) * Den(a), Den(a) * Den(b))
END Add;

PROCEDURE Mul(a, b: Fraction): Fraction;
BEGIN
  RETURN Make(Num(a) * Num(b), Den(a) * Den(b))
END Mul;

PROCEDURE Equal(a, b: Fraction): BOOLEAN;
BEGIN
  RETURN (Num(a) = Num(b)) AND (Den(a) = Den(b))
END Equal;

END FracMath.

Add and Mul read the parts with Num and Den and create the result with Make, which reduces it. Equal compares the parts; since every fraction is reduced, equal values have equal parts.

arith.mod
MODULE arith;
FROM InOut IMPORT WriteString, WriteLn;
FROM Fractions IMPORT Fraction, Make, Write, Free;
FROM FracMath IMPORT Add, Mul;

VAR
  a, b, sum, product: Fraction;

BEGIN
  a := Make(1, 2);
  b := Make(1, 3);
  sum := Add(a, b);
  product := Mul(a, b);
  Write(a); WriteString(" + "); Write(b);
  WriteString(" = "); Write(sum); WriteLn;
  Write(a); WriteString(" * "); Write(b);
  WriteString(" = "); Write(product); WriteLn;
  Free(a); Free(b); Free(sum); Free(product)
END arith.

Each call of Add or Mul returns a new fraction, and the program frees all four at the end.

$ gm2 -c FracMath.mod
$ gm2 arith.mod FracMath.o Fractions.o -o arith
$ ./arith
1/2 + 1/3 = 5/6
1/2 * 1/3 = 1/6

Comparing opaque values

Clients may assign values of an opaque type and compare them with = and #. Because the values are pointers, the operators compare addresses, not contents.

compare.mod
MODULE compare;
FROM InOut IMPORT WriteString, WriteLn;
FROM Fractions IMPORT Fraction, Make, Write, Free;
FROM FracMath IMPORT Equal;

VAR
  a, b, c: Fraction;

PROCEDURE Report(name: ARRAY OF CHAR; same: BOOLEAN);
BEGIN
  WriteString(name);
  IF same THEN WriteString(": yes") ELSE WriteString(": no") END;
  WriteLn
END Report;

BEGIN
  a := Make(1, 2);
  b := Make(2, 4);
  c := a;
  Write(a); WriteString(" and "); Write(b); WriteLn;
  Report("a = b", a = b);
  Report("a = c", a = c);
  Report("Equal(a, b)", Equal(a, b));
  Free(a);
  Free(b)
END compare.

a and b are both 1/2 but are two records, so a = b is false. c := a copies the pointer, so a = c is true; c is not freed separately, because it is the same fraction as a. To compare values, a client calls Equal.

$ gm2 compare.mod FracMath.o Fractions.o -o compare
$ ./compare
1/2 and 1/2
a = b: no
a = c: yes
Equal(a, b): yes

Freeing intermediate results

Every function that returns a new fraction hands the client a value to free. A nested call hides one of them, and the counter in Fractions shows it.

leak.mod
MODULE leak;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Fractions IMPORT Fraction, Make, Write, Free, Live;
FROM FracMath IMPORT Add;

VAR
  a, b, c, t, sum: Fraction;

BEGIN
  a := Make(1, 2);
  b := Make(1, 3);
  c := Make(1, 6);

  sum := Add(Add(a, b), c);
  Write(sum); WriteLn;
  Free(sum);
  WriteString("live after the nested call: "); WriteCard(Live(), 0); WriteLn;

  t := Add(a, b);
  sum := Add(t, c);
  Free(t);
  Write(sum); WriteLn;
  Free(sum);
  WriteString("live with a temporary: "); WriteCard(Live(), 0); WriteLn;

  Free(a); Free(b); Free(c);
  WriteString("live at the end: "); WriteCard(Live(), 0); WriteLn
END leak.

Add(Add(a, b), c) computes 5/6 in the inner call and passes it to the outer one, but no variable holds it, so it can never be freed. After the sum is freed, four fractions are live instead of three. The second calculation keeps the intermediate result in t and frees it, so the count does not grow. The one fraction left at the end is the one lost in the nested call. With opaque types on the heap, every expression that creates a value needs a variable to free it.

$ gm2 leak.mod FracMath.o Fractions.o -o leak
$ ./leak
1/1
live after the nested call: 4
1/1
live with a temporary: 4
live at the end: 1

An account type

The last example is a bank account. The module guarantees that a balance never drops below zero and counts every deposit and withdrawal; a client can only ask for a change.

Accounts.def
DEFINITION MODULE Accounts;

TYPE
  Account;

PROCEDURE Open(owner: ARRAY OF CHAR): Account;
PROCEDURE Deposit(a: Account; amount: CARDINAL);
PROCEDURE Withdraw(a: Account; amount: CARDINAL): BOOLEAN;
PROCEDURE Balance(a: Account): CARDINAL;
PROCEDURE Report(a: Account);
PROCEDURE Close(VAR a: Account);

END Accounts.

Account is opaque. Open creates an account for an owner, Close destroys it, and the other procedures work on an open account. Withdraw reports whether it succeeded.

Accounts.mod
IMPLEMENTATION MODULE Accounts;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
FROM Strings IMPORT Assign;

TYPE
  Account = POINTER TO AccountRec;
  AccountRec = RECORD
    owner: ARRAY [0..31] OF CHAR;
    balance: CARDINAL;
    moves: CARDINAL
  END;

PROCEDURE Open(owner: ARRAY OF CHAR): Account;
VAR
  a: Account;
BEGIN
  NEW(a);
  Assign(a^.owner, owner);
  a^.balance := 0;
  a^.moves := 0;
  RETURN a
END Open;

PROCEDURE Deposit(a: Account; amount: CARDINAL);
BEGIN
  INC(a^.balance, amount);
  INC(a^.moves)
END Deposit;

PROCEDURE Withdraw(a: Account; amount: CARDINAL): BOOLEAN;
BEGIN
  IF amount > a^.balance THEN
    RETURN FALSE
  END;
  DEC(a^.balance, amount);
  INC(a^.moves);
  RETURN TRUE
END Withdraw;

PROCEDURE Balance(a: Account): CARDINAL;
BEGIN
  RETURN a^.balance
END Balance;

PROCEDURE Report(a: Account);
BEGIN
  WITH a^ DO
    WriteString(owner); WriteString(": ");
    WriteCard(balance, 0); WriteString(" after ");
    WriteCard(moves, 0); WriteString(" moves"); WriteLn
  END
END Report;

PROCEDURE Close(VAR a: Account);
BEGIN
  DISPOSE(a)
END Close;

END Accounts.

The record holds the owner, the balance and the number of moves. Withdraw refuses an amount larger than the balance, so the CARDINAL balance can never wrap around. Report opens the record with WITH a^, which only the implementation module may do.

bank.mod
MODULE bank;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Accounts IMPORT Account, Open, Deposit, Withdraw, Balance, Report, Close;

VAR
  anna, ben: Account;

PROCEDURE Transfer(from, to: Account; amount: CARDINAL);
BEGIN
  WriteString("transfer "); WriteCard(amount, 0);
  IF Withdraw(from, amount) THEN
    Deposit(to, amount);
    WriteString(": done")
  ELSE
    WriteString(": refused")
  END;
  WriteLn
END Transfer;

BEGIN
  anna := Open("Anna");
  ben := Open("Ben");
  Deposit(anna, 500);
  Deposit(ben, 120);
  Transfer(anna, ben, 200);
  Transfer(ben, anna, 400);
  Transfer(ben, anna, 320);
  Report(anna);
  Report(ben);
  WriteString("total: "); WriteCard(Balance(anna) + Balance(ben), 0); WriteLn;
  Close(anna);
  Close(ben)
END bank.

Transfer belongs to the client: it is built from Withdraw and Deposit and deposits only when the withdrawal succeeded. Ben cannot send 400 with a balance of 320, so the second transfer is refused. The money in the two accounts stays 620.

$ gm2 -c Accounts.mod
$ gm2 bank.mod Accounts.o -o bank
$ ./bank
transfer 200: done
transfer 400: refused
transfer 320: done
Anna: 620 after 3 moves
Ben: 0 after 3 moves
total: 620

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared opaque types in definition modules, completed them as pointers in implementation modules, written constructors and destructors, kept every value valid, built new operations on the exported interface, compared opaque values, freed intermediate results and written an account type. The modules article covers definition and implementation modules, and the pointers article covers the heap storage behind every opaque value.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.