Special Member FunctionsÂ
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 described in this section are as follows:
Constructors. Enable automatic initialization of objects.
Destructors. Perform cleanup after objects are explicitly or implicitly destroyed.
Conversion functions. Convert between class types and other types.
operator new function. Dynamically allocates storage.
operator delete function. Releases storage allocated using the new operator.
Assignment operator (operator=). Used when an assignment takes place.
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 Member-Access Control. The following table summarizes how member and friend functions behave.
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? | Will Compiler Generate Function if User Does Not? |
---|---|---|---|---|---|
Constructor |
No |
No |
No |
Member |
Yes |
Copy 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 |
new |
Yes |
No |
void* |
Static member |
No |
delete |
Yes |
No |
void |
Static member |
No |
Other member functions |
Yes |
Yes |
Yes |
Member |
No |
Friend functions |
No |
No |
Yes |
Friend |
No |