Create copy constructor. - C++ Class

C++ examples for Class:Constructor

Description

Create copy constructor.

Demo Code

#include <iostream>
using namespace std;
class sample {/*from   www.j a v  a2s  . com*/
   public:
   int v;
   // Default constructor.
   sample() {
      v = 0;
      cout << "Inside default constructor.\n";
   }
   // Parameterized constructor.
   sample(int i) {
      v = i;
      cout << "Inside parameterized constructor.\n";
   }
   // Copy constructor.
   sample(const sample &obj) {
      v = obj.v;
      cout << "Inside copy constructor.\n";
   }
};
// Pass an object to a function. The copy constructor
// is called when a temporary object is created to
// hold the value passed to x.
int timestwo(sample x) {
   return x.v * x.v;
}
// Return an object from a function. The copy constructor
// is called when a temporary object is created for the return value.
sample factory(int i) {
   sample s(i);
   return s;
}
int main()
{
   cout << "Create samp(8).\n";
   sample samp(8);
   cout << "samp has the value " << samp.v << endl;
   cout << endl;
   cout << "Create samp2 and initialize it with samp.\n";
   sample samp2 = samp;
   cout << "samp2 has the value " << samp2.v << endl;
   cout << endl;
   cout << "Pass samp to timestwo().\n";
   cout << "Result of timestwo(samp): " << timestwo(samp) << endl;
   cout << endl;
   cout << "Creating samp3.\n";
   sample samp3;
   cout << endl;
   cout << "Now, assign samp3 the value returned by factory(10).\n";
   samp3 = factory(10);
   cout << "samp3 now has the value " << samp3.v << endl;
   cout << endl;
   // Assignment does not invoke the copy constructor.
   cout << "Execute samp3 = samp.\n";
   samp3 = samp;
   cout << "Notice that the copy constructor is not used "
   << "for assignment.\n";
   return 0;
}

Result


Related Tutorials