POINTERS TO AN OBJECT AND AN ARRAY OF OBJECTS

Examine the example program named INHERIT7.CPP for examples of the use of an array of objects and a pointer to an object.

In this program, the objects are instantiated from an inherited class and the intent of this program is to illustrate that there is nothing magic about a derived class.

The program is identical to the first program in this chapter until we get to the main program where we find an array of 3 objects of class car declared in line 52. It should be obvious that any operation that is legal for a simple object is legal for an object that is part of an array, but we must be sure to tell the system which object of the array we are interested in by adding the array subscript as we do in lines 56 through 62. The operation of this portion of the program should be very easy for you to follow, so we will go on to the next construct of interest.

You will notice, in line 65, that we do not declare an object of type truck but a pointer to an object of type truck. In order to use the pointer, we must give it something to point at which we do in line 67 by dynamically allocating an object. Once the pointer has an object to point to, we can use the object in the same way we would use any object, but we must use the pointer notation to access any of the methods of the object. This is illustrated for you in lines 68 through 72, and will be further illustrated in the example program of chapter 12 in this tutorial.

Finally, we deallocate the object in line 73. You should spend enough time with this program to thoroughly understand the new material presented here, then compile and execute it.