abelenky
abelenky

Reputation: 64682

"No appropriate default constructor available" in C++11

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?


Edit Some have suggested the problem is with SomeObj and its constructor.
SomeObj is also a P.O.D. class, using just initializers to set its data.

Upvotes: 0

Views: 206

Answers (2)

TartanLlama
TartanLlama

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

Puppy
Puppy

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

Related Questions