C++ rules for special member functions

C++ has several special member functions that are defined by the compiler even if not defined by the user. These special member functions are the default constructor, the copy constructor, the copy assignment operator, the move constructor, the move assignment operator, and the destructor. However, there are many rules for what is defined and in which circumstances. For instance, if no special member function is defined by the user then all of them are implicitly defined by the compiler. On the other hand, if a copy constructor or copy assignment operator is defined by the user, then the move constructor and move assignment operator are not defined by the compiler.

To make it easier to comprehend all the rules, the following table describes what is defined by the compiler based on what is defined by the user.

Default constructorCopy constructorCopy operator=Move constructorMove operator=Destructor
NothingYESYESYESYESYESYES
Any constructorNOYESYESYESYESYES
Default constructorNOYESYESYESYESYES
Copy constructorNONOYESNONOYES
Copy operator=YESYESNONONOYES
Move constructorNODELETEDDELETEDNONOYES
Move operator=YESDELETEDDELETEDNONOYES
DestructorYESYESYESNONONO

In the table above, on the horizontal, we have the special member functions that the compiler defines and on the vertical the functions the user may define. You should read the table as follows:

YESthe special member function is defined by the compiler
NOthe special member function is not defined by the compiler
NOthe special member function is not defined by the compiler since it is defined by the user
YESthe special member function is defined by the compiler but this is deprecated and may be removed in the future
DELETEDthe special member function is defined by the compiler as deleted

7 Replies to “C++ rules for special member functions”

  1. There is a mistake in your table, if the destructor is defined by the user, then the move assignment operator is NOT defined by the compiler.

    I think the table could therefore be simplified somewhat (less rows, less columns) by grouping together copy constructor and copy assignment operator and the one hand, and move constructor and move assignment operator on the other. It would be less scary.

  2. Thanks for pointing to the error. I have fixed the table.

    As a side note, the yellow YES means that the function is generated by the compiler but that is deprecated and may be removed in the future.

  3. Thank you! This is great. Just one correction – the [default constructor/default constructor] box should be gray

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.