Classes and Pointers


And just like any other data type, you can have pointers to classes, pointers to pointers to classes, pointers to pointers to pointers to classes, etc (get the point?). To see how they are implemented, lets take a look at the classic example, the linked-enchilada-list.

#include <iostream.h>

class EnchiladaNode {
  public:
    int data;
    EnchiladaNode* next;
};

void main(void) {
  EnchiladaNode *top = new EnchiladaNode;

  top->data = 5;
  top->next = new EnchiladaNode;
  top->next->data = 6;
  cout << "First there's a ";
  cout << top->data;
  cout << " then there's a ";
  cout << top->next->data << endl;
  delete top->next;
  delete top; 
}

In the above example there are a few important things to notice and remember. First of all there is the sytax for accessing class members from a pointer to a class which is the same as how to access struct members from a pointer to a struct, using the -> notation. also notice that like other forms of pointers, we had to allocate the memory for the class using a new, and then deallocate it at the end using a delete.


Table of Contents

Classes | More Class Basics | Class Methods | Public and Private
Using Public and Private | Classes and Pointers | Exercises