views:

199

answers:

3

I was wondering why an error like this would occur.

no matching function for call to 'Foo::Foo()'

in code for a copy constructor? Assume Foo is just an object with normal fields ( no dynamically allocated memory, etc. ), and the only constructor it has defined is a constructor that takes one argument.

I didn't even know the constructor needed to be considered though. If the code says something like

bar = thing.bar; //

and bar is of Foo type, with the specifications described above, shouldn't it just generate a shallow copy and be done with it? Why does a default constructor need to be invoked?

+7  A: 

If you don't define a constructor, the compiler will generate a default constructor, however if you do define a constructor (Like a copy constructor) the compiler won't generate the default constructor, so you need to define that constructor too.

John Weldon
+1 for correct answer.
Greg D
Thanks. I thought the compiler only wouldn't define the default constructor if I defined a default constructor, not just any constructor.
Anonymous
+3  A: 

It sounds like you've defined the copy constructor without defining any other constructor.

Once you declare an constructor explicitly, the compiler no longer provides a default constructor for you. Consequently, you no longer have a mechanism to construct an object of the class in the first place (and therefore wouldn't be able to copy it).

jamesdlin
+1  A: 

If, as you say, you're doing "something like

bar = thing.bar;

it's presumably in the body of your class's copy ctor -- so the bar field gets initialized with its class's default ctor first, then uses that class's assignment operator for this statement. If bar's class only has a copy ctor, no default ctor, you'll need to add a bar(thing.bar) clause before your class's copy ctor opening { and remove that assignment (generally a good idea anyway, but mandatory under the "no default ctor" condition).

Alex Martelli