class Foo
{
public:
explicit Foo() {}
explicit Foo(Foo&) {}
};
Foo d = Foo();
error: no matching function for call to \
Foo d = Foo();
should be
Foo d;
The first line creates a Foo instance and then copies it to d;
The compiler is telling you... Use this:
Foo(const Foo&) {}
class Foo
{
public:
explicit Foo() {}
explicit Foo(const Foo&) {}
};
Foo d = Foo()
First, neither the default constructor nor the copy constructor should ever be explicit
. You only need to make a constructor explicit
if it takes a single argument of some other type, to prevent implicit conversion from that type. The copy constructor takes a reference to the class itself, so there is no danger of an unwanted conversion.
Second, make sure that the copy constructor takes a const
reference.
Third, Foo f;
is the right way to have a default-constructed object of class foo. Note that Foo f();
is wrong, because the compiler will interpret that as a declaration of function f()
which returns an object of class Foo
.
Fourth, if you have written your own copy constructor, then you should also write the assignment operator.
class Foo
{
Foo() {} // no need to make explicit. Nothing to convert from.
Foo(const &Foo f) {} // again, nothing wrong with conversion from Foo to Foo
explicit Foo(int a) {} // need explicit to prevent accidental passing of an int
// to a function that takes Foo as an argument
};