Pointers to Class Objects and Pointers as Class Data Members


Pointers to Class Objects

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:

image from book

 ClassName * thePointer; 

image from book

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:

image from book

 ClassName anObject; thePointer = &anObject; 

image from book

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:

image from book

 (*thePointer).aNonPrivateMember .... 

image from book

In this case *thePointer is another name for anObject. While the arrow operator may be used as follows:

image from book

 thePointer -> aNonPrivateMember 

image from book

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:

image from book

 ClassName* thePointer = new ClassName; 

image from book

would define thePointer to be a pointer to an unnamed object of the class: ClassName. The following:

image from book

 ClassName* thePointer = new ClassName[5]; 

image from book

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.

Pointers as Data Members

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:

image from book

 private:    char *thePointer;    float amount; 

image from book

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.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net