How to layout a template class and what it's good for.Template class is exactly what it seems, a template. It allows you to define a class and involve variables of unknown type T. Thus the class can be implemented as a universal class for any group of elements sharing a class or base class.
A stack is a good example which can be used for many types.
CODE Example:
template <class T>
class Stack
{
int max;
T** rep; // a dynamic array of pointers to T
int size;
public:
Stack(int); // a constructor
~Stack( ) {delete [ ] rep;} // destructor
bool empty( );
void push(T&);
T& pop( );
};
You could add many more methods to this to expand the explanation, but this shows the use.
NOTE: the method body for the member functions have not been written, these are only the declarations.
This stack is implemented using a dynamic array, which is created by passing the max size to the stack upon creating the object. To create an unending stack, you could implement a Vector or Linked List.
Now the stack can handle objects of typ T which can be any type. If you use primatives, they must all be of the same type in a single stack to prevent chaos in your methods.
If you wish to use only user definded objects, then you could write the methods to call subsequent methods inside your object based on the current pointer on the stack.
NOTE this last idea requires that all mixed objects be derived from a single superclass or base class. as the declaration of this stack even as a template requires a given type.
Stack integerStack(20);
Questions/Comments:
[email protected]