Declaring classes in C++

A simple class is declared in C++ in the same way as a struct, except that it also contains function declarations. Such functions may either be declared in full or as prototypes. It is normal to only give prototypes in the class declaration and to provide their implementation separately, unless they are requested to be expanded inline. This allows more control over the building and use of libraries including classes, since the definitions can be in separate include files used by both the implementation file and user programs. We shall usually write our C++ this way.

An example of a class declaration.

// definition file named listhead.h for list package

typedef struct List_Item {
      int val;
      List_Item * next;
   } List_Item;

class List_Head {

   List_Item* next;
   
public:

   void insert(List_Item *);

   void printout();

};


// implementation file for the List_Head class

#include "listhead.h"

void List_Head::insert(List_Item * Item) {
   Item->next = next;
   next = Item;
}

void List_Head::printout() {
   List_Item * curr;
   curr = next;
   while(curr) cout << curr->val << '\n';
}

The implementation matches function declarations to the prototypes given inside the class body. It prefixes the name of each function with the class name to which it is bound followed by a double colon. Before a class object can be created, implementations must be provided for all its functions.

Next note in series

Back to index