Pointers: this, new and delete

C++ offers two functions, and one special pointer to be used PIC(pointers) with object. The new command allocates memory for an object, and returns a pointer to that memory location.

The delete command is used to free the allocated memory created by the new command. Using the person class example from above, we can create a pointer to the object, and allocate memory for the object by writing:

person *bob= new person;

The asterisk before bob indicates that this is a pointer to an object of class person. The new person portion of the command allocates enough memory to contain a person sized object.

To release this memory location we type: delete bob;. The delete command will not get rid of the pointer variable *bob, just the memory allocated for the object that bob points to.

C++ also provides a method for an object to find its own location. The this keyword is a pointer to the current object. If an object needed to pass its location to another object, it could do so by using the this pointer. Example:

object2->find_me( this );

The find_me function in object2 would receive the address of the calling object..

Back to Object Oriented Concepts