Quiz: C++ Classes and Special Member Functions

Module 2 of 8 · Medium

Quick Quiz

1. A `Matrix` class owns a heap-allocated buffer via `double* _data`. You define a destructor that calls `delete[] _data`. You do **not** define a copy constructor. What happens when you write `Matrix b = a;`?

2. What does the following copy assignment operator do incorrectly? ```cpp Matrix& Matrix::operator=(const Matrix& other) { delete[] _data; _n = other._n; _data = new double[_n]; std::copy(other._data, other._data + _n, _data); return *this; } ```

3. After a move operation, the moved-from object is in a **destroyed** state and can no longer be used in any way.

4. Which function signature correctly declares a **move constructor** for `class Matrix`?

5. In the copy-and-swap idiom for copy assignment: ```cpp Matrix& operator=(Matrix other) { swap(*this, other); return *this; } ``` When is the destructor called on the old resource?

6. If you declare `Matrix(const Matrix&) = delete;`, then writing `Matrix b = a;` is a compile error, but `Matrix b(std::move(a));` is still valid (assuming a move constructor exists).