Reputation: 64682
I'm trying to use C++11 initializers to avoid writing unnecessary default constructors. However, I get the error "no appropriate default constructor available", and don't understand why.
Here's a simplified version of my code:
struct Foo
{
double fieldA { 0.0 }; // Initializer
short fieldB { 0 }; // Initializer
SomeObj myObj; // Use default ctor of SomeObj
// Foo() = default; // this line doesn't help!
Foo(const SourceData& src)
{ // Error: No Appropriate Default Ctor!
fieldA = src.GetFieldA();
fieldB = src.GetFieldB();
myObj = src.GetObject();
}
};
I don't see any reason that compiler generated default constructor wouldn't be available and wouldn't work. Even when I "encourage" the compiler to generate a default constructor, I still get the same message.
If I actually write out a default-ctor, then it does work. But that defeats the purpose of using initializers in place of a constructor, right?
Upvotes: 0
Views: 206
Reputation: 65610
Most likely this is referring to the default constructor of SomeObj
rather than Foo
. If you don't initialize your member data in the initialization list, they'll be default-constructed before your constructor body is entered. You probably want to do this:
Foo(const SourceData& src) :
fieldA {src.GetFieldA()}, fieldB {src.GetFieldB()}, myObj {src.GetObject()}
{ }
Upvotes: 0
Reputation: 146910
You should typically just initialize the objects in the initializer list instead of default-constructing them and then assigning to them.
However, there's no reason why the compiler should accept a user-written empty default constructor over a defaulted one.
The most likely explanation is that SomeObj
has no default constructor, or possibly that it is explicit
.
Upvotes: 1