Question

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 ?

Était-ce utile?

La solution

Because the copy constructor you explicitly define for sample doesn't ask for core'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 its core sub-object. By writing it the way you have done, you have chosen not to initialise the core sub-object using obj. Since you haven't said how you do want it initialised, the compiler just uses core'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 sample does ask for the core sub-object to be initialised using core's copy constructor, hence the observed behaviour.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top