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
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) { }
Every class that has a pointer data member should provide the "Big Three":
Called automatically when an object is:
passed by value to a function
returned (by value) as a function result
declared with an initialization from an existing object of the same class
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]; }
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; }
Called when object is about to go away:
In IntList.cpp
IntList::~IntList() { delete [] items; }