CIS 150 Pointers

Objectives

  • Create an object and save a pointer to it.
  • Use pointers with objects.
  • Free the memory used by an object.

Pointer overview

  • See the arrays and pointers notes for general pointer information.
  • We need to use pointers if we dynamically allocate objects using the new keyword.
  • We also need to remember to deallocate memory we are finished using to avoid memory leaks.
  • Memory leaks can be especially bad in long running programs, frequently called functions, and loops with many iterations.
  • Pointers are often used with objects.

Using pointers with objects

// Assume we have a class named: Pet Pet p0("Snowball"); // creates a new Pet object Pet* p1 = new Pet("Fido"); // creates a new object pointed to by p1 cout << p0.getName() << endl; // accessing function using member-of notation cout << p1->getName() << endl; // accessing function using pointer notation p0.setName("Casper"); // accessing function using member-of notation p1->setName("Spot"); // accessing function using pointer notation delete p1; // frees memory used by object p1 pointed to // we don't need to free p0 memory since C++ does that automatically