Consider the sample code below:
#include <iostream>
using namespace std;
class core
{
public:
core(const core& obj)
{
cout << "core copy ctor called\n";
}
core()
{
cout << "core default ctor called\n";
}
};
class sample : public core
{
public:
sample()
{
cout << "sample default ctor called\n";
}
#if 0
sample(const sample& obj)
{
cout << "sample copy ctor called\n";
}
#endif
};
int main()
{
sample s1;
sample s2 = s1; //Line1
return 0;
}
Type1: Copy constructor not declared explicitly for class sample
(Type1 is shown in the code above. Then the copy constructor of class sample is implicitly generated by the compiler).
When the statement, Line1 is executed, first the copy constructor of class core is invoked, and then the copy constructor of class sample is invoked.
Type2: Copy constructor defined explicitly for class sample
When the statement, Line1 is executed, first the default constructor of class core is invoked, and then the copy constructor of class sample is invoked.
Question:
Why is this difference in behavior for copy constructor as mentioned in Type1 and Type2 ?
Because the copy constructor you explicitly define for
sampledoesn’t ask forcore‘s copy constructor to be invoked. You’d have to write: core(obj)if you wanted to make that happen.Put another way, when you write an explicit copy constructor, you are taking charge of the copy construction of
sample, including itscoresub-object. By writing it the way you have done, you have chosen not to initialise thecoresub-object usingobj. Since you haven’t said how you do want it initialised, the compiler just usescore‘s default constructor instead, hence the behaviour in the second case you outline.By contrast, in the first case, the compiler-generated default copy constructor for
sampledoes ask for thecoresub-object to be initialised usingcore‘s copy constructor, hence the observed behaviour.