CS 70

When Classes Allocate Memory…

class Barn {
 public:
    Barn();
    Barn(size_t numCows);
    void feed();

    // Disable copying and assignment
    Barn(const Barn& other) = delete;
    Barn& operator=(const Barn& rhs) = delete;
 private:
    size_t cowCapacity_;
    Cow residentCow_;
};
  • LHS Cow speaking

    So far, our Barn class is a little silly…

  • Duck speaking

    You mean because we store the number of Cows as a size_t, but we can only hold one Cow?

  • LHS Cow speaking

    Yeah, that. Wouldn't it be nice if we could actually hold more than one Cow in our Barn?

  • Dog speaking

    Ooh, I know a way to hold more than one Cow! We can have an array of Cows instead of a single Cow!

  • LHS Cow speaking

    We can if we use what we learned last week about dynamic memory allocation!

Reflection

Why does the memory for our Cows need to be on the heap instead of the stack?

  • Horse speaking

    Hay! But I thought primitive arrays had to be fixed size!??

  • LHS Cow speaking

    It's true that the array size can't change after it's created, but if we use the heap, we're deciding how much space to allocate at runtime (when we call new) rather than at compile time (when we write declare a variable).

A Class with Dynamically Allocated Memory

  • LHS Cow speaking

    Here's what our Barn might look like in memory if we want to be able to have different numbers of Cows each time.

What should the type of residentCows_ be?

What should the value of residentCows_ be?


  • Hedgehog speaking

    Okay, I guess, but how do we get to the point where the memory looks like those diagrams?

  • LHS Cow speaking

    We're going to have some extra work to do in each step of our object's lifetime!

  • Hedgehog speaking

    Oh, no.

(When logged in, completion status appears here.)