Practice Using C++ Pointers

Lab 5
CSCI 112


Goals:
Get some experience using pointers.  Specifically, using the following C++ components:  new, delete, *, &

Completing these labs will help you with the next programming assignment (p3).


Instantiating a class using dynamic memory
Recall that you can dynamically allocate memory using the C++ new operator

And you can delete dynamically allocated memory using the C++ delete operator

Consider the following example:
#include "foo.h"

int
main()
{
    Foo *f;

    f = new Foo(1,2);

    ... blah blah blah ...

    delete f;

}
In the above example, class Foo is instantiated using the new operator.  It is deleted using the delete operator.


Exercise 1:
Create a directory for lab 5
Copy all the files from ~tyson/112/src/lab5 into your new lab 5 directory (don't forget the dot "." at the end of the second line)
$ cd <to your lab 5 directory>
$ cp   ~tyson/112/src/lab5/*   .

These files are also available on the web: src/lab5.

Exercise 2:
in main() create a pointer variable that points to an object of type Foo

    hint: a pointer to an integer would be    int *p;

Use the new operator to construct a new Foo object

Print that object by calling Foo's print() function

Use the delete operator to delete that object

Compile and run your program. 

What functions are called?   (each member function in Foo has a cout statement, so you can see what is called)

Exercise 3:
Create an instantiation of Bar WITHOUT using dynamic memory.

    hint: an instantiation of an integer without using dynamic memory would look like:   int i(42);

What member functions of Bar are called? 

When exactly do you think they are called?

Exercise 4:
Create a function called print_foo() in main.cpp that takes a pointer to a Foo as its only argument (you have to figure out the syntax).

Have this function print out the object passed to it by calling Foo's print function (hint: you will need to use ->).

In main() pass the object you created dynamically (in exercise 2) to this new function.

Did it print the correct Foo object?

In main() create an instantiation of Foo WITHOUT using dynamic memory (just like in exercise 3 above).

Pass this variable directly to print_foo().

Why doesn't this work?

What can you do to make it work?

Exercise 5:

In main() create an array of 10 pointers to Foo.

Using the new operator, create 10 new Foo objects with values of your choice and have the 10 pointers in your array point to the new Foo objects.

Call Foo::print() for each of the 10 Foo object.