At the point of creation the user may wish to define certain initial actions for the object, such as setting up starting values. It is useful if this sequence can be invoked automatically. C++ defines this initialisation sequence in a special function called a constructor.
C++ requires the user to return objects explicitly, arguing that this is more efficient than having some complex garbage collector interrupt execution from time to time. Other languages assume that users prefer to have the extra convenience and security of a garbage collector. Its main advantages are:
At the point of destruction the user may wish to invoke some terminating actions, such as list returning all its members to the heap by deleting them as well. C++ defines this termination sequence in a special function called a destructor.
The constructor has the same name exactly as its class. The destructor has the same name exactly, preceded by a tilde.
Construction occurs at the point where its declaration is reached, for an automatic variable of a class type, or when new is used to allocate space in the heap, for a class pointer.
Destruction occurs when the block containing its declaration terminates, for an automatic class variable, or when delete is used to return to the heap the space allocated to a pointer to a class.
List class extended with constructor and destructor
// definition file named listhead.h for list package #include<iostream.h> #define NULL 0 typedef struct List_Item { int val; List_Item * next; }; class List_Head { List_Item* next; public: void insert(List_Item *); void printout(); List_Head(); ~List_Head(); };Simple text version of listhead.h.
// implementation file for 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'; curr = curr->next; } } List_Head::List_Head() { next = NULL; } List_Head::~List_Head() { while(next) { List_Item * temp = next; delete next; next = temp->next; } }Simple text version of listhead.cpp.
User program for lists
#include "listhead.h" void main() { List_Head L; for(int i=1; i<=10; i++) { List_Item * n = new List_Item; n->val = i; L.insert(n); } L.printout(); }Simple text version of main program.