Chapter 10: Pointers

Chapter Goals

Pointers and Memory Allocation

Pointers and Memory Allocation (Syntax 10.1 new Expression)

Syntax 10.1 : new Expression

new type_name
new type_name(exprssion1, expression2, . . . , expressionn)
Example:
new Time;
new Employee("Lin, Lisa", 68000)
Purpose: Allocate and construct a value on the heap and return a pointer to the value.

Pointers and Memory Allocation (Syntax 10.1 Pointer Variable Definition)

Syntax 10.2 : Pointer Variable Definition

type_name* variable_name;
type_name* variable_name = expression;
Example:
Employee* boss;
Product* p = new Product;
Purpose: Define a new pointer variable, and optionally supply an initial value.

Pointers and Memory Allocation

Pointers and Memory Allocation (Syntax 10.3 Pointer Dereferencing)

Syntax 10.3 : Pointer Dereferencing

*pointer_expression
pointer_expression->class_member
Example:
*boss
boss->set_salary(70000)
Purpose: Access the object to which a pointer points.

Pointers and Memory Allocation

Deallocating Dynamic Memory

Deallocating Dynamic Memory (Syntax 10.4 delete Expression)

Syntax 10.4: delete Expression

delete pointer_expression
Example:
delete boss;
Purpose: Deallocate a value that is stored on the heap and allow the memory to be reallocated.

Deallocating Dynamic Memory

Common Uses for Pointers (Optional Attributes)

Common Uses for Pointers (Sharing)

Common Uses for Pointers (department.cpp)

Arrays and Pointers

Arrays and Pointers

Pointers to Character Strings

Pointers to Character Strings