MC logo
Copying Objects
[^] CSc 220 Home
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Safe Integer Array Class] [Safe Integer Array Implementation] [Bounds Error Demo] [Object Copy Demo] [No Copies For Me, Please] [Hidden Calls]
Reading: pp 202–204

This small section shows an implementation of a simple ADT in C++: An array with bounds checking. Its main purpose is to illustrate the need for destructors, copy constructors, and assignment operators to correctly implement a C++ ADT which allocates storage dynamically.

In C++, objects are often copied, on assignment and when passed as parameters. By default, the system does this by simply copying each data field in one object to the same field in another. But if one of the fields is a pointer allocated with new, this simply copies the pointer so that both objects point to the same allocated block. Usually, that's not what you want. To deal with this, C++ allows the programmer to specify how copying is performed so it can always be done correctly.