An example might make object-oriented programming concepts clearer. A stack is a common programming construct, permitting data to be stored and retrieved in a Last-In, First-Out (LIFO) manner, that is, the last data element placed on the stack is the first element that is retrieved from the stack.

The data structure for the stack describes the stack, a place to store the data put on the stack and a variable to keep track of the location of the top of the stack. Given the definition of the data structure, multiple instances of the stack can be declared within a program.

There are two basic operations that can be performed on a stack: pushing data onto the stack and popping data off from the stack. It also is beneficial to dynamically create a stack. Functions to perform these activities must be defined.

The following sample code shows the definition of a stack data structure and functions and the implementation for the Push function:

/* Define the stack */
struct stackType
{
  void *stackArray[STACK_SIZE];
  int stackTop;
};
typedef struct stackType Stack;

/* Define the stack's functions */
Stack *Create();                /* Create a new stack                  */
void Push(Stack *thisStack,     /* Push an element onto the stack      */
          void *nextElement);
void *Pop(Stack *thisStack);    /* Pop an element off from the stack   */

/* The definition of the Push function is provided as an example.  */
/* The rest of the functions would be defined in a similar manner. */
void Push(Stack *thisStack, void *nextElement)
{
  thisStackstackArray[thisStackstackTop] = nextElement;
  thisStackstackTop++;
}

A client program might use this stack to create a stack of words needing interpretation, as in the following sample code:

main()
{
  Stack *WordStack;

  char *Subject = "Emily";
  char *Verb    = "eats";
  char *Object  = "ice cream";
  char *NextWord;

  WordStack = Create();
  Push(WordStack, Object);
  Push(WordStack, Verb);
  Push(WordStack, Subject);
     .
     .
     .

  while (NextWord = Pop(WordStack))
  {
    printf("%s\n", NextWord);
     .
     .
     .
  }
}

The stack is an example of a class. The stack contains two data elements, stackArray and stackTop, and supports three methods: Create, Push, and Pop. WordStack is an object of class Stack; it also can be called an instance of a stack.

Methods must know the specific object on which they are to operate, which is called the target object or, sometimes, the receiving object. Notice that each method (except Create) takes as its first parameter a pointer to the target object. This is because a program might have many objects of a given class, and each is a potential target for the class methods.


[Back] [Next]