5
votes

My c++ book says this (lippman, c++ primer, fifth ed., p. 508):

The synthesized default constructor is defined as deleted if the class ... has a const member whose type does not explicitly define a default constructor and that member does not have an in-class initializer. (emphesis mine)

Why then does this code produce an error?

class Foo {
  Foo() { }
};

class Bar {
private:
  const Foo foo;
};

int main() {
  Bar f; //error: call to implicitly-deleted default constructor of 'Bar'
  return 0;
}

The rule above seems to indicate that it should not be an error, because Foo does explicitly define a default constructor. Any ideas?

3
I don't think your quote is relevant here, because Foo does explicitly define a default constructor. It is not true that the quote says that your code is OK. - Kerrek SB
@KerrekSB you're right, but then the book must be omitting some other rules I should also know about, because none of the other rules mention anything relevant about the default constructor. (there are 4 rules on when the copy control members and the default constructor are deleted.) - user2015453

3 Answers

7
votes

To fix your error. You need to make Foo::Foo() public.

class Foo
{
public:
    Foo() { }
};

Otherwise I do believe it is private.

Is this what your looking for?

5
votes

The default constructor is omitted when a a class construction isn't trivial.

That in general means that either there is an explicit constructor that receives parameters (and then you can't assume that it can be constructed without those parameters)

Or if one of the members or base classes need to be initiated in construction (They themselves don't have a trivial constructor)

1
votes

I think that this should work

class Foo {
  public:
  Foo() { }
};

class Bar {
public:
  Bar() : foo() {}
private:
  const Foo foo;
};