Classes like structures and other data types may also have pointers to class objects. As with other pointers, they must be defined as pointers to the specific class. Such a pointer could be defined as in the following:
ClassName * thePointer;
As with other pointers, they must be initialized by assigning the address of the object to which they point by using the address operator & as in the following statements:
ClassName anObject; thePointer = &anObject;
As with structures, pointers to class objects may be used to manipulate the class members by using the dereference operator: * or the arrow operator ->. Pointers may be used with the dereference operator as in following:
(*thePointer).aNonPrivateMember ....
In this case *thePointer is another name for anObject. While the arrow operator may be used as follows:
thePointer -> aNonPrivateMember…
In addition to these uses of a pointer, the dynamic memory allocation operators new and delete may be used with pointers to a class object as well. For example:
ClassName* thePointer = new ClassName;
would define thePointer to be a pointer to an unnamed object of the class: ClassName. The following:
ClassName* thePointer = new ClassName[5];
would define thePointer to be a pointer to the first byte of an array of 5 ClassName objects. See example bank9.cpp When you use pointers and dynamic memory allocation, don't forget to use the delete operator.
In addition to pointers to class objects, it is also possible to have pointers as class data members as well. For example it is possible to have:
private: char *thePointer; float amount;
See example bank10.cpp.
Warning: When pointers are data members, it is recommended that the class have an explicit destructor to ensure that the memory whose address the pointer contains is deleted.