Default constructor/destructor outside the class?

Vincent picture Vincent · Jan 10, 2013 · Viewed 8.4k times · Source

Is the following legal according to the C++11 standard (= default outside the definition of the class) ?

// In header file
class Test
{
    public:
        Test();
        ~Test();
};

// In cpp file
Test::Test() = default;
Test::~Test() = default;

Answer

Adam H. Peterson picture Adam H. Peterson · Jan 16, 2013

Yes, a special member function can be default-defined out-of-line in a .cpp file. Realize that by doing so, some of the properties of an inline-defaulted function will not apply to your class. For example, if your copy constructor is default-defined out-of-line, your class will not be considered trivially copyable (which also disqualifies it from being recognized as a POD). Similarly, a default-defined out-of-line destructor will disqualify your type from being trivial (or POD).

This can be useful if you wish to have a non-inline copy-constructor and control over where it is defined (perhaps to take control over generated template definitions it will require), but don't wish to manually define it yourself with a hand-crafted member-initializer list, which would be laborious and could go stale under maintenance.