Defining Classes


Constructors and member initialization lists

A constructor is called:

when an object is declared:

 

 

 

when an object is dynamically allocated:

 

 

 

 

In Java: data members are initialized automatically before a constructor executed

In C++: before body of constructor is executed, each data member (field) that is an object is initialized by calling the field's no-arg constructor

 

 

 

 

 

Member initialization lists

In IntList.cpp

IntList::IntList() : 
items(new int[SIZE]), numItems(0), arraySize(SIZE) 
{
}

IntList::IntList(int size) : 
items(new int[size]), numItems(0), arraySize(size) 
{
}

The "Big Three"

Every class that has a pointer data member should provide the "Big Three":

Copy Constructor

Called automatically when an object is:

In IntList.cpp

IntList::IntList(const IntList &L) : 
items(new int[L.arraySize]), numItems(L.numItems), arraySize(L.arraySize) {
    for (int k = 0; k < numItems; k++)
        items[k] = L.items[k];
}

Copy Assignment (operator=)

In IntList.cpp

IntList & IntList::operator=(const IntList &L) {
    if (this == &L)
        return *this;
 
    else {
        delete [] items;               
        items = new int[L.arraySize];  
        arraySize = L.arraySize;      
 
        for (numItems = 0; numItems < L.numItems; numItems++)
            items[numItems] = L.items[numItems];
    }
 
    return *this;
}

Destructor

Called when object is about to go away:

In IntList.cpp

IntList::~IntList() {
    delete [] items;
}