| | | | | |

Static Member Functions 2

  • A static method that does not access any (static) class data is effectively a stand-alone function whose scope is restricted to the class scope.
  • Method NewArray is a "helper" function that encapsulates a repetitive housekeeping task into one place where it can be maintained.
  • Makes all of the other method implementations that use dynamic memory easier to read, and it means that the policy for handling a failed allocation can be changed in one place while ensuring consistent adherence to the policy.
  • class IntArray
    {
    private:
      static int* NewArray (size_t sz);
      ...
    } ;
    
    int* IntArray::NewArray (size_t sz)
    {
      int * ptr = new(std::nothrow) int [sz];
      if (ptr == 0)
      {
        std::cerr << "** Allocation failure in class IntArray\n";
        exit (1);  // replaceable handler code
      }
      return ptr;
    }
    

| | Top of Page | 5. C++ Classes Part 2: Advanced Features - 20 of 22