| | | | | |

Copy Constructor 2

  • Code for creating copy is made by the compiler
  • If available, compiler calls the copy constructor after allocating memory for objects
  • class IntArray
    {
    public:
      IntArray  ( size_t sz = 10 , int ivalue = 0 );
      ~IntArray ();
      IntArray  (const IntArray& a);
      ...
    } ;
    
    IntArray::IntArray  (const IntArray& a) : size_(a.size_) , data_(nullptr)
    {
      data_ = new int [size_];  // check for failed allocation
      for (size_t i = 0; i < size_; ++i)
        data_[i] = a.data_[i];
    }
    

| | Top of Page | 6. C++ Classes Part 2: Advanced Features - 4 of 22