Templates

 

If we need a stack of int AND a stack of double we could declare and define:

 

stackint.h

 

#ifndef STACKINT_H

#define STACKINT_H

 

#include <stddef.h>

 

class StackInt {

public:   

    StackInt();

    StackInt(
        const StackInt& srcStack );

    ~StackInt();

    void Push( /* in */ int newItem );

    int Top() const;

    int Pop();

    bool IsEmpty() const;

    bool IsFull() const;

    int Size() const;

private:

    struct Node

    {

        int   item;

        Node* next;

    };

    Node* top;

    int   size;

};

 

#endif

 

stackdouble.h

 

#ifndef STACKDOUBLE_H

#define STACKDOUBLE_H

 

#include <stddef.h>

 

class StackDouble {

public:   

    StackDouble ();

    StackDouble (

        const StackDouble & srcStack );

    ~ StackDouble ();

    void Push( /* in */ double newItem );

    double Top() const;

    double Pop();

    bool IsEmpty() const;

    bool IsFull() const;

    int Size() const;

private:

    struct Node

    {

        double item;

        Node*  next;

    };

    Node* top;

    int   size;

};

 

#endif

 

stackint.cpp

 

#include "StackInt"

 

int StackInt::Pop()

{

    Node* oldPtr;

    int   item;

 

    item   = top->item;

    oldPtr = top;

    top    = top->next;

    delete oldPtr;

    size--;

    return item;

}

 

...

 

stackdouble.cpp

 

#include "StackDouble"

 

double StackDouble::Pop()

{

    Node* oldPtr;

    double  item;

 

    item   = top->item;

    oldPtr = top;

    top    = top->next;

    delete oldPtr;

    size--;

    return item;

}

 

...

 

app.cpp

 

#include "stackint.h"

#include "stackdouble.h"

 

void main()

{

    StackInt    stackInt;

    StackDouble stackDouble;

    ...

}

 

 

It is far less work to define a single templated Stack class.

 

stack.h

 

#ifndef STACK_H

#define STACK_H

 

#include <stddef.h>

 

template< class Item >

class Stack

{

public:    

    Stack();

    Stack( const Stack& srcStack );

    ~Stack();

    void Push( /* in */ Item newItem );

    Item Top() const;

    Item Pop();

    bool IsEmpty() const;

    bool IsFull() const;

    int Size() const;

private:

    struct Node

    {

        Item  item;

        Node* next;

    };

    Node* top;

    int   size;

};

 

#endif

 

 

Also in stack.h

 

template< class Item >

Item Stack<Item>::Pop()

{

    Node* oldPtr;

    Item  item;

 

    item = top->item;

    oldPtr = top;

    top = top->next;

    delete oldPtr;

    size--;

    return item;

}

 

app.cpp

 

#include "stack.h"

 

void main()

{

    Stack<int>    stackInt;

    Stack<double> stackDouble;

    ...

}