Lecture 2
Common questions
The things people most often get confused about in object oriented data types.
What is the difference between an ADT and a data structure?ADTs
An ADT specifies *what* operations exist and what they mean (a stack supports push, pop, top). A data structure is *how* it is built. The same stack ADT can be implemented with an array or with linked nodes, and callers shouldn't care which.
What is the difference between a data structure and an algorithm?ADTs
A data structure organizes data so it can be accessed (like a library's shelves). An algorithm is a finite series of steps that solves a problem (look up the code, find the shelf, fetch the book). Programs need both.
How do I tell a syntax error from a logical error?Programming process
A syntax error stops compilation. A logical error compiles and runs but gives wrong output, such as printing 11 when the answer is 10. Runtime errors (crashes) show up while the program runs.
Why does the last valid index equal n - 1?Arrays
Indexing starts at 0, so an array of size n has indices 0 to n - 1. C++ does not check bounds, so a[n] silently reads or writes past the end, which is undefined behaviour.
int a[3] = {7, 4, 9};
std::cout << a[1]; // 4 (second element)
// a[3] is out of boundsWhy do I have to pass an array's length to a function?Arrays
A C-style array parameter is adjusted to a pointer, so the length is lost. const int a[] is really const int* a. Pass the count as a second parameter.
int findMax(const int a[], int n); // n carries the lengthWhat does const do in const int a[]?Arrays
It forbids changing the elements through that parameter, so a[0] = 1; will not compile. Reading a[0] and passing the size are still fine. Use it whenever the function only reads.
Why does a 2D array parameter need the column size but not the row count?2D arrays
Memory is row-major, so the address of a[r][c] is computed as r * COLS + c. The compiler needs COLS for that, but the row count is only needed for loops, so you pass it separately.
void display(const int a[][3], int rows); // OK
// void display(const int a[][], int rows); // errorWhat is the difference between p and *p?Pointers
p is the address stored in the pointer. *p is the object at that address. Assigning to *p changes the target object; assigning to p makes it point somewhere else.
Where do local variables live compared to new objects?Heap
Locals have automatic storage (the stack) and are cleaned up when their scope ends. new creates objects on the heap (free store), which live until released with delete (or by an owner). An object's storage duration and its scope are not the same thing.
Why set a pointer to nullptr after delete?Heap
After delete, the pointer still holds the old address, which is no longer valid. Setting it to nullptr makes a later delete p; harmless and lets you test p != nullptr. It does not fix other pointers that hold the same address.
int* p = new int(8);
delete p;
p = nullptr;What goes wrong in delete z; cout << *z;?Heap
That is a use-after-free: the memory no longer belongs to you, so reading it is undefined behaviour (it might print the old value, garbage, or crash). Read or print the value *before* deleting. Deleting the same allocation twice is also undefined behaviour.
Why must new[] be paired with delete[]?Dynamic arrays
They are the matched array forms of allocation and release. new T[n] must be released with delete[], and new T with delete. Mixing them is undefined behaviour.
int* a = new int[3];
delete[] a; // not: delete a;Why does the resize function take int*& a instead of int* a?Dynamic arrays
The function replaces the caller's pointer with the new block. With plain int* a it would only change a local copy, leaving the caller with a pointer to the deleted old array. size is passed by reference for the same reason, so the caller sees the new capacity.
void extendArray(int*& a, int& size) {
int* b = new int[size * 2]{};
for (int i = 0; i < size; ++i) b[i] = a[i];
delete[] a;
a = b;
size *= 2;
}When should I use std::vector instead of new[]?Dynamic arrays
Almost always when you need a resizable array. A vector grows, copies and frees its memory automatically, which removes the leaks, double deletes and resize bugs of raw arrays. Learn the raw mechanics to understand what it does for you.
Why does my pointer into an array break after I resize it?Resizing
Resizing allocates a new block and deletes the old one, so every pointer into the old block (like int* middle = a + 2;) now dangles. Recompute it from the new block after the resize (middle = a + 2;), or store an index instead, which stays valid.
int* a = new int[4]{2, 4, 6, 8};
int* middle = a + 2;
shrink(a); // old block deleted
middle = a + 2; // refresh before reading
std::cout << *middle;What is the difference between size and capacity?Resizing
size is how many elements are in use. capacity is how many the allocated block can hold. When size == capacity the array is full and must grow. Copy only size elements when growing, since the rest are unused.
How should grow handle an empty array?Resizing
Capacity 0 doubles to 0, so special-case it: grow to 1 when capacity == 0, otherwise double. delete[] data; is safe when data is nullptr, so the same code works for an empty array.
int next = capacity == 0 ? 1 : capacity * 2;What goes wrong with delete a; and i <= 3 in a shrink function?Resizing
delete a; on memory from new[] is undefined behaviour; use delete[] a;. A loop bound of i <= 3 copies four elements (indices 0 to 3) into a block of size 3, writing one past the end. Use i < 3.
Why make the data private and expose functions instead?Classes
So the class can keep its invariants. In ScoreLog, only add and removeLast change scores and count, so count can never go above 4 or below 0. Public data would let any caller break that. This is the ADT idea: callers use operations, not the representation.
Why should a failed add or removeLast leave everything unchanged?Classes
Callers can then rely on the object being valid after any call. removeLast(int& removed) must not touch removed when the log is empty, otherwise the caller may read a garbage "removed" value after a false result.
bool removeLast(int& removed) {
if (count == 0) return false; // removed untouched
removed = scores[--count];
return true;
}Why is removed a reference parameter?Classes
The function already returns a bool for success, so the removed value comes back through the reference. With plain int removed the function would only change its own copy.
Why does larger() return the first value when they are equal?Templates
first < second ? second : first only picks second when it is strictly larger, so ties fall through to first. The tie rule comes from the < comparison, not from the order of the arguments you pass to the constructor.
Why is larger() marked const but swapValues() isn't?Templates
const promises the member function doesn't modify the object. larger() only reads, while swapValues() changes first and second. A const member can be called on const objects, so mark every read-only member const.
Why use long long for the row sum in bestRow?2D arrays
Adding three ints can overflow int, which is undefined behaviour. Widening the first term (static_cast<long long>(a[i][0]) + ...) makes the whole sum long long. The strict > keeps the first row when sums tie, and the function returns -1 when rows is 0.
No questions match.
Ready to check yourself? Take the quiz →