Page 252 - DCAP404 _Object Oriented Programming
P. 252

Unit 11: Pointers and Dynamic Memory Management




                  for  (n=0;  n<i;  n++)                                                        Notes
              {
                      cout  <<  “Enter  number:  “;
                cin >> p[n];
              }
                  cout  <<  “You  have  entered:  “;
                  for  (n=0;  n<i;  n++)
                cout << p[n] << “, “;
                  delete[]  p;
            }
              return  0;
          }      How many numbers would you like to type? 5
          Enter number : 75
          Enter number : 436

          Enter number : 1067
          Enter number : 8
          Enter number : 32
          You have entered: 75, 436, 1067, 8, 32,
          Notice how the value within brackets in the new statement is a variable value entered by the
          user (i), not a constant value:
                 p= new (nothrow) int[i];
          But the user could have entered a value for i so big that our system could not handle it. For
          example, when I tried to give a value of 1 billion to the “How many numbers” question, my
          system could not allocate that much memory for the program and I got the text message we
          prepared for this case (Error: memory could not be allocated).





             Notes  Remember that in the case that we tried to allocate the memory without specifying
             the nothrow parameter in the new expression, an exception would be thrown, which if it’s
             not handled terminates the program.
          It is a good practice to always check if a dynamic memory block  was successfully allocated.
          Therefore, if you use the nothrow method, you should always check the value of the pointer
          returned. Otherwise, use the exception method, even if you do not handle the exception. This
          way, the program will terminate at that point without causing the unexpected results of continuing
          executing a code that assumes a block of memory to have been allocated when in fact it has not.

          11.5.2 The this Pointer

          C++ uses a unique keyword called “this” to represent an object that invokes a member function.
          ‘this’ is a pointer that points to the object on which this function was called. The pointer ‘this’
          acts as an implicit argument to  all the  member function  apart from the explicit arguments
          passed to it.




                                           LOVELY PROFESSIONAL UNIVERSITY                                   245
   247   248   249   250   251   252   253   254   255   256   257