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 ?