C++ defines several kinds of functions that can be declared only as class members—these are called “special member functions.” These functions affect the way objects of a given class are created, destroyed, copied, and converted into objects of other types. Another important property of many of these functions is that they can be called implicitly (by the compiler).
The special member functions are described briefly in the following list:
Constructors. These functions enable automatic initialization of objects. See “Constructors”.
Destructors. These functions perform cleanup after objects are explicitly or implicitly destroyed. See “Destructors”.
Conversion functions. These are used to convert between class types and other types. See “Conversion Functions”.
The new operator. This is used to dynamically allocate storage. See “The operator new Function”.
The delete operator. This is used to release storage allocated using the new operator. See “The operator delete Function”.
The assignment operator (operator=). This operator is used when an assignment takes place. See “Compiler-Generated Copying”.
All of the items in the preceding list can be user-defined for each class.
Special member functions obey the same access rules as other member functions. The access rules are described in Chapter 10, “Member-Access Control.” Table 11.1 is a summary of how member and friend functions behave.
Table 11.1 Summary of Function Behavior
Function Type |
Is Function Inherited from Base Class? | Can Function Be Virtual? |
Can Function Return a Value? |
Is Function a Member or Friend? |
Is Function Generated by the Compiler? |
Constructor | No | No | No | Member | Yes | |
Destructor | No | Yes | No | Member | Yes | |
Conversion | Yes | Yes | No | Member | No | |
Assignment (operator=) | No | Yes | Yes | Member | Yes | |
Function call (operator( )) | Yes | Yes | Yes | Member | No | |
Subscript (operator[ ]) | Yes | Yes | Yes | Member | No | |
Member selection (–>) | Yes | Yes | Yes | Member | No | |
Compound Assignment (+=, –=, and so on) | Yes | Yes, Yes | Either | No | ||
new | Yes | No | void* | Static member | No | |
delete | Yes | No | void | Static member | No | |
Operators not listed above | Yes | Yes | Yes | Either | No | |
Other member functions | Yes | Yes | Yes | Member | No | |
Friend functions | No | No | Yes | Friend | No |