Page 126 - DCAP404 _Object Oriented Programming
P. 126

Unit 6: Constructors and Destructors




                                                                                                Notes


             Notes  Note that C++ selects one constructor by matching the signature of the method
             being called.  Also, once you define a constructor method, the default constructor  is
             overridden and is not available to the class.  Therefore you must also define a constructor
             method resembling the default constructor method having no parameters.

          6.1.2 Destructor

          When a program no longer needs an instantiated object it destroys it. If you do not supply a
          destructor function, C++ supplies a default destructor for you, unknown to you. The program
          uses the destructor to destroy the object for you.
          When should you define your own destructor function? In many cases you do not need a destructor
          function. However, if your class created dynamic objects, then you need to define your own
          destructor in which you will delete the dynamic objects. This is because dynamic objects cannot
          be deleted on their own. So, when the object is destroyed, the dynamic objects are deleted by the
          destructor function you define.



             Did u know?  Should we explicitly call a destructor on a local variable?
             No!

             The destructor will get called again at the close } of the block  in which the local  was
             created. This is a guarantee of the language; it happens automatically; there’s no way to
             stop it from happening. But you can get really bad results from calling a destructor on the
             same object a second time! Bang! You’re dead!
          A destructor function has the same  name as  the class,  and does not have  a returned  value.
          However you must precede the destructor with the tilde sign, which is ~ .
          The following code illustrates the use of a destructor against dynamic objects:
          #include  <iostream>
          using  namespace  std;


          class  Calculator
              {
                  public:
                  int *num1;
                  int *num2;


                          Calculator(int  ident1,  int  ident2)
                      {
                          num1 = new int;
                          num2 = new int;








                                           LOVELY PROFESSIONAL UNIVERSITY                                   119
   121   122   123   124   125   126   127   128   129   130   131