Special member functions
In the C++ programming language, special member functions are functions which the compiler will automatically generate if they are used, but not declared explicitly by the programmer.
The automatically generated special member functions are:
- Default constructor if no other constructor is explicitly declared.
- Copy constructor if no move constructor and move assignment operator are explicitly declared.
- Move constructor if no copy constructor, copy assignment operator, move assignment operator and destructor are explicitly declared.
- Copy assignment operator if no move constructor and move assignment operator are explicitly declared.
- Move assignment operator if no copy constructor, copy assignment operator, move constructor and destructor are explicitly declared.
- Destructor
The compiler generated functions will be
public, non-virtual and the copy constructor and assignment operators will receive const& parameters.Example
The following example depicts two classes: for which all special member functions are explicitly declared and for which none are declared.- include
- include
- include
class Implicit : public Explicit ;
Signatures
Here are the signatures of the special member functions:| Function | syntax for class MyClass |
| Default constructor | MyClass; |
| Copy constructor | MyClass; |
| Move constructor | MyClass noexcept; |
| Copy assignment operator | MyClass& operator=; |
| Move assignment operator | MyClass& operator= noexcept; |
| Destructor | virtual ~MyClass; |
C++03
In C++03 before the introduction of move semantics the special member functions were:- Default constructor
- Copy constructor
- Copy assignment operator
- Destructor