Pointers

Chapter 10: Pointers

Chapter Goals

Pointers and Memory Allocation

Syntax 10.1: new Operator

new type_name
new type_name(expression1, 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.

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.

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.

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.

Deallocating Dynamic Memory

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.

Common Uses for Pointers (Optional Attributes)

Common Uses for Pointers (Sharing)

Common Uses for Pointers (department.cpp)


Arrays and Pointers


Pointers to Character Strings