# Object Construction A short lab from early in the course. Two small programs, each making one idea concrete: when the special member functions fire, and what happens when you index past the end of a heap array. ## Tracing constructors and destructors `object_construction.cpp` defines a `cat` class with a name and an age. Every special member function prints a line when it runs: - the default constructor prints `called default constructor` - the copy constructor prints `called copy constructor` - the destructor prints `called destructor` - the overloaded `operator+=` prints `called assignment` The driver in `object_test.cpp` creates a couple of cats and adds one to another. Running it, you watch the output and match each printed line to a line of code. The point is to see, without a debugger, the order things construct and destruct in, and to notice that the destructors run at the end of scope in reverse order of construction. ```mermaid sequenceDiagram participant main participant a as cat a participant b as cat b main->>a: default constructor main->>b: default constructor main->>a: operator+= (b) main->>b: destructor main->>a: destructor ``` ## Array bounds and undefined behavior `array_bounds_check.cpp` allocates two `char` arrays on the heap, one of size 5 and one of size 20, then writes `n` characters into the first where `n` comes from the user. C++ does not check array bounds, so when `n` is larger than 5 the writes run off the end of the first array and into whatever memory follows, which is often the second array. The program prints the contents of both so you can see the overrun happen. The header comments record the lab questions and my answers: nothing is allocated to catch the overflow, the two arrays sit a fixed distance apart in memory, and the fix is to check `n` against the array size before writing. It is a hands-on look at why bounds checking matters and why a class like the [Custom String](Custom-String.md) tracks its own size. ## Build and run There is no Makefile for this lab. Compile the two programs directly: ```sh cd object_construction g++ -std=c++11 object_construction.cpp object_test.cpp -o object_test && ./object_test g++ -std=c++11 array_bounds_check.cpp -o bounds_check && ./bounds_check ``` For `bounds_check`, enter a value larger than 5 to see the overrun. ## Notes This is the smallest project in the set and it is meant to be read and run, not extended. It earns its place because the lessons (value semantics and bounds tracking) are exactly what the larger projects depend on.