Tuesday, September 19, 2006
Dynamic Memory and Pointers

Topics


Output:

The area of boxes[0], of width 0 and height 0 is 0.
The area of boxes[1], of width 1 and height 1 is 1.
The area of boxes[2], of width 2 and height 2 is 4.
The area of boxes[3], of width 3 and height 3 is 9.
 

Using references instead of pointers (extra material not in Deitel book.  If this confuses you, just stick with pointers.)

    - You can also access data or objects on the heap using references.
    - Once created, the reference variable looks and acts just like a stack variable, not a pointer.
    - You must dereference the pointer created by new, and use it to initialize a reference.
    - Once a reference is created, it cannot be reassigned like a pointer.  It will always represent only that one object on the heap.

Class& object = *new Class; //default constructor  
or
Class&
object = *new Class(arg);

    - Now you use your object using the dot operator, just like an object created on the stack:

object.someFunction();

     - Your reference variable is treated exactly like a normal variable, including the way it is passed as a parameter.

// pass by value
void afunction(Class object);    // prototype
afunction(object);               // call
 

// pass by value using const reference
void afunction(const Class& object); // prototype
afunction(object);                   // call
 

// pass by reference using a pointer
void afunction(Class* object
);     // prototype
afunction(&object);                // call

 

// pass by reference using a reference
void afunction(Class& object
);     // prototype
afunction(object);                // call

 

  - Notice in the last example, you are passing a reference to a reference.  This will work fine with no change of syntax from passing any normal variable to a reference parameter.

    - Always destroy your object when you are finished, returning the memory to the available heap.
    - To delete the object, you must turn the reference back into a pointer by taking its address with the ampersand operator.
 

delete &object;

 

Readings

Deitel and Deitel Fifth Edition, Sections 8.1, 8.2, 8.3, 8.4, 8.7, 8.8, and 8.9 .

 

Back to Csc 125 Computer Science II, Programming in C++
  Scott Badman   Office: B132   Phone: 353-2250   sbadman@parkland.edu  

Parkland College, 2400 W. Bradley Avenue, Champaign, IL 61821