Copy semantics (part 2)

This lesson contains approximately 25 minutes of video content.

Implementing a deep copy policy

The rule of zero and the rule of three

Activity: Rule of three for a two-dimensional array

Graded Playground Autograder

Activity Prompt:

This activity requires you to define the rule of three functions for the class Array2D. The copy policy you implement must perform a deep copy.

The objects derived from this class blueprint maintain a two-dimensional array on the free store through their int** array_ data member. array_ points to an array of height_ int* objects. Each int* in turn points to an array of width_ int objects. When implementing your deep copy policy, if the ArrayOfArrays object being copied from is empty (defined as its array_ is nullptr), ensure the object being initialized or assigned to has the same values as it would upon default constructed.

Member functions you are to implement
public:
~Array2D(); Destructor. Deallocates all dynamic objects associated with array_.
Array2D(const Array2D& rhs); Copy constructor.
  • Initializes the data member height_ with rhs.height_ and width_ with rhs.width_.
  • Allocates a two-dimensional array on the free store and assigns the address to array_. After allocation, array_ must point to an array of height_ int* objects. Each int* in array_ in turn points to an array of width_ int objects.
  • Performs a deep copy of rhs.array_ into array_.
Array2D& operator=(const Array2D& rhs); Copy Assignment Operator.
  • Checks for self-assignment. Immediately returns *this in the event of self-assignment.
  • Since this object exists, deallocate all dynamic objects associated with array_.
  • Assigns the data member height_ with rhs.height_ and width_ with rhs.width_.
  • Allocates a two-dimensional array on the free store and assigns the address to array_. After allocation, array_ must point to an array of height_ int* objects. Each int* in array_ in turn points to an array of width_ int objects.
  • Performs a deep copy of rhs.array_ into array_.
  • Return a self-reference to the caller.
Provided member functions
public:
Array2D() = default; Default constructor.
#include "solution.hpp" int main() {}
#ifndef SOLUTION_HPP #define SOLUTION_HPP class Array2D { public: Array2D() = default; Array2D(const Array2D& rhs); Array2D& operator=(const Array2D& rhs); ~Array2D(); private: unsigned int height_ = 0; unsigned int width_ = 0; int** array_ = nullptr; }; #endif
#include "solution.hpp"