In the following example, struct A
does not have default constructor. So both struct B
and struct C
inherited from it cannot get compiler-generated default constructor:
struct A {
A(int) {}
};
struct B : A {
B() = default; //#1
};
struct C : A {
C();
};
C::C() = default; //#2
#1. In struct B
, defaulted default constructor is declared inside the class, and all compilers accept it, with only Clang showing a warning saying that explicitly defaulted default constructor is implicitly deleted [-Wdefaulted-function-deleted]
#2. But defaulted default constructor declared outside of struct C
generates a compiler error. Demo: https://gcc.godbolt.org/z/3EGc4rTqE
Why does it matter where the constructor is defaulted: inside or outside the class?
Note that if you actually try and instantiate B
then you'll also get the error that B::B()
is deleted: https://gcc.godbolt.org/z/jdKzv7zvd
The reason for the difference is probably that when you declare the C
constructor, the users of C
(assuming the definition is in another translation unit) have no way of knowing that the constructor is in fact deleted. At best this would lead to some confusing linker error, at worst it'd just crash at runtime. In the case of B
all users of B
will immediately be able to tell that the default constructor is deleted so it does no harm (even if it makes no sense as warned by clang) to declare it as defaulted.