What are all the member-functions created by compiler for a class? Does that happen all the time?

C++98/03

If they are needed,

  1. the compiler will generate a default constructor for you unless you declare any constructor of your own.
  2. the compiler will generate a copy constructor for you unless you declare your own.
  3. the compiler will generate a copy assignment operator for you unless you declare your own.
  4. the compiler will generate a destructor for you unless you declare your own.

As Péter said in a helpful comment, all those are only generated by the compiler when they are needed. (The difference is that, when the compiler cannot create them, that’s Ok as long as they aren’t used.)


C++11

C++11 adds the following rules, which are also true for C++14 (credits to towi, see this comment):

  • The compiler generates the move constructor if
    • there is no user-declared copy constructor, and
    • there is no user-declared copy assignment operator, and
    • there is no user-declared move assignment operator and
    • there is no user-declared destructor,
    • it is not marked deleted,
    • and all members and bases are moveable.
  • Similarly for move assignment operator, it is generated if
    • there is no user-declared copy constructor, and
    • there is no user-declared copy assignment operator, and
    • there is no user-declared move constructor and
    • there is no user-declared destructor,
    • it is not marked deleted,
    • and all members and bases are moveable.

Note that these rules are a bit more elaborate than the C++03 rules and make more sense in practice.

For an easier understanding of what is what in the above:

class Thing {
public:
    Thing();                        // default constructor
    Thing(const Thing&);            // copy c'tor
    Thing& operator=(const Thing&); // copy-assign
    ~Thing();                       // d'tor
    // C++11:
    Thing(Thing&&);                 // move c'tor
    Thing& operator=(Thing&&);      // move-assign
};

Further reading: if you are a C++-beginner consider a design that does not require you to implement any of five a.k.a The Rule Of Zero originally from an article written by Martinho Fernandes.

Leave a Comment