Page 128 - DCAP404 _Object Oriented Programming
P. 128

Unit 6: Constructors and Destructors




          4.   …………………….. are called at the point an object is created.                         Notes
          5.   Specifying a constructor with a return type is an error, as is taking the ……………….. of a
               constructor.

          6.   A destructor takes no ………………… and has no return type.

          6.2 Copy Constructor

          A copy constructor method allows an object to be initialized with another object of the same
          class.   It implies that the values stored in data members of an existing object can be copied into
          the data variables of the object being constructed, provided the objects belong to the same class.
          A copy constructor has a single parameter of reference type that refers to the class itself as shown
          below:

          abc::abc(abc  &  a)
          {
                 x=a.x;

                 y=a.y;
          }
          Suppose we create an object myabc1 with two integer parameters as shown below:

          abc  myabc1(1,2);
          Having created myabc1, we can create another object of abc type, say myabc2  from myabc1, as
          shown below:

          myabc2=abc(&  myabc1);
          The data values of myabc1 will be copied into the corresponding data variables of object myabc2.
          Another way of activating copy constructor is through assignment operator.  Copy constructors
          come into play when an object is assigned another object of the same type, as shown below:

          abc  myabc1(1,2);
          abc  myabc2;
          myabc2=myabc1;
          Actually assignment operator(=) has been overloaded in C++ so that copy constructor is invoked
          whenever an object is assigned another object of the same type.



             Did u know?  What is the difference between the copy constructor and the assignment
             operator?

             (a)  If a new object has to be created before the copying can occur, the copy constructor
                 is used.
             (b)  If a new object does not have to be created before the copying can occur, the assignment
                 operator is used.









                                           LOVELY PROFESSIONAL UNIVERSITY                                   121
   123   124   125   126   127   128   129   130   131   132   133