9

Difference between =default and empty constructor with no arguments?

Is there difference between:

MyClass() {}
MyClass() = default;
user3111311
  • 6,863
  • 7
  • 31
  • 40

2 Answers2

5

Overall No there is not. ;)

It will do overall the same, but not exactly (like sftrabbit, Nawaz, and 0x499602D2 suggest it, thanks by the way).

You will find an answer to your question here ;)

Community
  • 1
  • 1
Axel Borja
  • 3,317
  • 6
  • 33
  • 46
  • 9
    It will do the same but it will change certain properties of the class (like whether it is trivial or not). – Joseph Mansfield Jan 16 '14 at 14:37
  • 2
    They're not exactly same. Both of them will return different value for [`std::is_trivial::value`](http://en.cppreference.com/w/cpp/types/is_trivial). – Nawaz Jan 16 '14 at 14:40
  • 1
    There *are* differences. The constructor with `= default` is `constexpr` and has `noexcept` specification. That, along with what the other comments say. – David G Jan 16 '14 at 15:12
  • @0x499602D2 An implicitly defined default constructor isn't *always* `constexpr`; it will only be `constexpr` if it would be well-formed to declare it as such. (Which IIRC requires that all members and bases have `constexpr` constructors. – Casey Jan 16 '14 at 16:01
0

So, this does not use constructors, but destructors. But it does show a point. The following code will compile, and no static assertions will fire.

This means that you have a user defined destructor in one example, and a __default destructor in the other.

#include <type_traits>

class X {
    public:
        ~X() {}
};

class Y {
    public:
        ~Y() = default;
};

static_assert(std::is_trivially_move_constructible<X>::value == false, "");
static_assert(std::is_trivially_move_constructible<Y>::value == true, "");
Bill Lynch
  • 76,897
  • 15
  • 123
  • 168
  • @Nawaz: Yeah. destructors. I wasn't aware of `std::is_trivial`, but I figured there was a test for the trivial move constructor existing, which should only happen in `Y`. It just proves a semantic point that `= default` does not mean `{}` in the general case. – Bill Lynch Jan 16 '14 at 14:44
  • Unless you meant the bolded part of the answer, where I meant to write destructor instead of constructor. – Bill Lynch Jan 16 '14 at 14:45