next up previous
Next: Some notes Up: From Modula-2 ADT's to Previous: Defining the interface

Defining the implementation

In Modula-2, the implementation of the stack class could look like:

IMPLEMENTATION MODULE IntStacks;
(* IntStacks; array implementation *)

FROM  Storage IMPORT
    Available,
    Allocate, Deallocate;

CONST 
    MaxSize      = 10;

TYPE 
    IntStack         = POINTER TO IntStackInstance;
    IntStackInstance = RECORD
                           top  : CARDINAL [0..MaxSize];
                           stack: ARRAY [1..MaxSize] OF INTEGER;
                       END;

PROCEDURE Push(VAR S: IntStack; e: INTEGER);
BEGIN
    WITH S^ DO
        INC(top);
        stack[top] := e
    END
END Push;

PROCEDURE Pop(VAR S: IntStack; VAR e: INTEGER);
BEGIN
    WITH S^ DO
        e := stack[top];
        DEC(top)
    END
END Pop;

PROCEDURE Empty(S: IntStack): BOOLEAN;
BEGIN
    RETURN (S^.top = 0)
END Empty;

PROCEDURE Full(S: IntStack): BOOLEAN;
BEGIN
    RETURN (S^.top = MaxSize)
END Full;

PROCEDURE Create(VAR S: IntStack): BOOLEAN;
BEGIN
    IF Available(SIZE(IntStackInstance)) THEN
        Allocate(S, SIZE(IntStackInstance));
        S^.top := 0;
        RETURN TRUE
    ELSE
        RETURN FALSE
    END
END Create;

PROCEDURE Terminate(VAR S: IntStack);
BEGIN
    Deallocate(S, SIZE(IntStackInstance));
END Terminate;

END IntStacks.

In C++, the implementation could look like:

// intstack.cc

#include "intstack.h"

const int maxsize = 10;

intstack::intstack()
{
    top_ = 0;
    stack_ = new int[maxsize];
}

intstack::~intstack()
{
    top_ = 0;
    delete[] stack_;
}

void intstack::push(int element)
{
    stack_[top_] = element;
    top_++;
}

void intstack::pop(int& element)
{
    top_--;
    element = stack_[top_];
}

bool intstack::empty()
{
    return (top_ == 0);
}

bool intstack::full()
{
    return (top_ == maxsize);
}

The #include "intstack.h" is needed because a class has to be defined before the implementation can be understood by the compiler. The rest of the implementation is just C++ code.

Any program that wants to use the stack class, has to include the header file in the source and has to link in the object file of the stack implementation.





SE Praktikum
Tue Aug 13 13:10:22 MET DST 1996