------------------------------------------------------------------------------
MC logo
No Copies For Me, Please
[^] 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]
If a class provides no copy constructor or assignment operator, the system provides one by default. The default copies (or assigns) each of the data fields individually. If some of the fields are pointers, this is often the wrong behavior, and a correct copy constructor and assignment operator should be provided. Sometimes, however, copying an object may be difficult, or may not make sense. In that case, copying can be prevented by declaring un-implemented methods:
class Whatever {
    ...
    Whatever(const Whatever &);
    Whatever & operator=(const Whatever &);
    ...
}; 
Do not put bodies for these functions in the implementation file. Any attempt to copy or assign an object of type Whatever will create a call to an un-defined function, which will create a compiler error. These functions are usually also declared private. This makes them even more illegal to call from outside, and, for a large program, will produce the error message earlier in the compile process, which can save time.

The 2011 standard adds a syntax to specifically eliminate these functions. Under the newer standard, you can say:

class Whatever {
    ...
    Whatever(const Whatever &) = delete;
    Whatever & operator=(const Whatever &) = delete;
    ...
}; 
This explicitly removes the functions to prevent copying and assignment.