CS 70

What About Arrays?

  • LHS Cow speaking

    So far today, we've only been looking at individual values. But we should also make sure we can reason about object lifetimes for arrays of values.

  • Hedgehog speaking

    That seems exponentially more complicated.

  • LHS Cow speaking

    It's not so bad!

Arrays are exactly the same as individual values; each phase of life just happens N times for an array of N values!

Allocation Phase

Allocation happens at the same time as for individual objects, but space for all N values is allocated at once.

  • Hedgehog speaking

    So Hedgehog array[5] (see here) will allocate space for five Hedgehogs on the stack?

  • LHS Cow speaking

    Exactly!

Initialization Phase

Initialization follows the same timing rules as individual objects, but will happen N times: once for each element of the array (in order).

  • RHS Cow speaking

    For a default-initialized array of N instances of a class, the default constructor will be called N times!

Use Phase

Use happens in the same way as for individual objects, for each individual element of the array.

Destruction Phase

Destruction follows the same timing rules as individual objects, but will happen N times: once for each element of the array.

For an array of N instances of a class, the destructor will be called N times!

  • LHS Cow speaking

    Mirroring the “destruction is the inverse of construction” idea, elements are destroyed in reverse order (i.e., last element destroyed first; first element destroyed last).

Deallocation Phase

  • Cat speaking

    I think I'm seeing a pattern here. Let me guess:
    Deallocation follows the same timing rules as individual objects, but space for all N _values is deallocated at once.

  • LHS Cow speaking

    Yup!

Practice Problem

Suppose we have the following member functions in our Cow class,

Cow::Cow() {
    cout << "Cow default constructor called" << endl;
}

Cow::~Cow() {
    cout << "Cow destructor called" << endl;
}

…and the following program that uses our Cow class,

int main() {
    Cow herd[5];
    Cow bessie;
    Cow mabel{3, 13};
}

When this program runs, how many times will the Cow default constructor called message be printed?

When this program runs, how many times will the Cow destructor called message be printed?

(When logged in, completion status appears here.)