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_;
};
So far, our
Barn
class is a little silly…You mean because we store the number of
Cow
s as asize_t
, but we can only hold oneCow
?Yeah, that. Wouldn't it be nice if we could actually hold more than one
Cow
in ourBarn
?Ooh, I know a way to hold more than one
Cow
! We can have an array ofCow
s instead of a singleCow
!We can if we use what we learned last week about dynamic memory allocation!
Reflection
Hay! But I thought primitive arrays had to be fixed size!??
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
Here's what our
Barn
might look like in memory if we want to be able to have different numbers ofCow
s each time.
Okay, I guess, but how do we get to the point where the memory looks like those diagrams?
We're going to have some extra work to do in each step of our object's lifetime!
Oh, no.
(When logged in, completion status appears here.)