CS 112 - Week 7 Lecture 1 - 2022-10-04
TODAY WE WILL:
* announcements
* aside: (static) arrays of objects
aside: pointers to objects (and more syntactic sugar)
aside: C++ fun fact: keyword this
* STOP 6: dynamic memory and arrays\
* STOP 6.5: dynamic arrays of objects!
arrays of pointers to objects!
dynamic arrays of pointers to objects!
* prep for next class
=====
* Current Reading:
Savitch, Chapter 9, pointers and dynamic memory
=====
* I posted a little handout with Homework 5:
"FUN FACTS about USING a user-defined class"
=====
* see notes in 112lect07-1.cpp!
=====
* C++ keyword this
* in C++, within a method of a class,
this is a special pointer that contains
the *address* of the CALLING object
SO, within a method,
this->name would be grabbing a name datafield
that is pointed to by this (and this is
pointing to the calling object)
=====
STOP 6 - dynamic memory and arrays!
=====
* how about dynamically allocating an array?
* hey, this is fairly straightforward!
new array_type[array_size]
...it dynamically allocates a chunk of memory
able to hold array_size instances of array_type,
and returns the address of the beginning of that
chunk
There IS special syntax for freeing a dynamically-
allocated array:
delete [] my_array_ptr;
^^ THIS tells the compiler to free ALL of the
array elements' memory, not just the first
array element's memory!!
* in between? treat that array ptr like an array name...!
-----
NOTE:
-----
* for both dynamic and static arrays,
it is considered POOR FORM to just change the address
they point to
(although for dynamic arrays it is considered FINE
to:
(1) deallocate the memory it points to
(2) THEN use new again to point to a newly-allocated
chunk of memory )