Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleted default constructor headache

Tags:

c++

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?

like image 873
user2015453 Avatar asked Jan 28 '13 14:01

user2015453


3 Answers

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?

like image 87
Xathereal Avatar answered Oct 16 '22 14:10

Xathereal


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)

like image 31
Yochai Timmer Avatar answered Oct 16 '22 14:10

Yochai Timmer


I think that this should work

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

class Bar {
public:
  Bar() : foo() {}
private:
  const Foo foo;
};
like image 23
Ed Heal Avatar answered Oct 16 '22 13:10

Ed Heal