Week 4: Building a better Python-like List type
Advantages and Disadvantages of arrays
Advantages:
Disadvantages:
Let's implement a better array -- a Dynamic Array.
PyList class
How this will differ from Vec class
In lab, you will create a Vec class -- also a dynamic array.
Dynamic allocation
Problem: you need space to store an array, but you don't know how big the array should be until runtime… What do you do?
new operator
new gets memory from the operating system.
Syntax:
int *arr = new int[capacity];
"argument" to new is a type, from which the number of bytes required can be computed
returns an address of (a pointer to) new memory, allocated from the heap
Stack vs. Heap
Local variables and parameters in a function are allocated on the stack.
Heap: other memory, allocated to the process by the operating system.
Implementing PyList
constructors
getSize() -- const method
append(const Item &it)
operator<<
destructor
When is a destructor called?
A class destructor is called when:
When do you need to implement a destructor?
C++ will create a destructor for you if you don't define it explicitly.
Q: When do you need to define it yourself?
A: If your code uses new to dynamically allocate memory from the heap, you need to implement the destructor to delete or delete[] that memory.
Implementing PyList (2)
copy constructor -- with deep copy
getItemAt()
operator[] -- two versions
removeAt() -- changes size but not capacity
When is a copy constructor called?
3 cases:
Pair p;
… put values in p …
Pair p2(p); // copy values from p to p2
When is a copy constructor called? (continued)
2. When object is passed to function using pass-by-value:
void f(Pair aPair) { … }
Pair p;
… snip …
f(p);
When is a copy constructor called? (continued)
3. When object is returned from a function:
Pair f() {
Pair p; // local variable
…
return p;
}
// in main
Pair p2 = f();
New Stuff
typedef
dynamic allocation
calling array ctor to initialize whole array
returning a reference (operator[])
overriding/defining operator overload.
const methods
overriding global << function.
destructor
copy constructor
implement removeAt()
changes mySize, but not myCapacity.
this pointer
Remember how in python each method had self as its first parameter:
class JumboShrimp:
def __init__(self, param):
…etc…
In C++, self is this -- a pointer to the object being read or modified or created. It is an implicit parameter (whereas self was an explicit parameter in python).
more about this
You can use this:
void setFirst(Item newVal) {
this->myFirst = newVal;
}
this-> means same as *(this).
You can call a method on this:
Item operator[](int idx) {
return this->getValueAt(idx); // instead of just getValueAt(idx);
}
Some people like to use this-> to emphasize they are using an instance variable or calling a method in the object itself.