Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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).

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top