I have been playing around with default constructors and noticed a weird behavior (from my point of view).
When I declare A() = default
, I get no linker error.
struct A
{
int a;
A() = default;
};
A a; // no linker error
However, when I declare A();
I get it.
struct A
{
int a;
A();
};
A a; // linker error - undefined reference to `A::A()`
Questions:
What's the difference between the two?
And if A();
produces a linker error, why is it supported in the first place? Any practical applications?
UPDATE (Follow-up Question)
For A();
why can't it be implicitly defined by the compiler if no definition is specified by the user?
In the first case the compiler itself defines the constructor. Take into account that in the first case the constructor declaration is at the same its definition.
In the second case as the constructor is a user-defined constructor then it is the user who must to define the constructor. In the second case there is only a declaration of the constructor.
Take into account that you can declare a constructor and then define it using the specifier default
.
For example
#include <iostream>
struct A
{
int a;
A();
};
A::A() = default;
int main()
{
A a;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With