| | | | <- prev | |

Classes with External Resources

  • Class constructor prepares a new object by creating an environment in which member functions operate.
  • When this environment acquires external resources, that resource must be handled carefully whenever the object is copied and also when the object goes out of scope.
  • Example:
  • class IntArray
    {
      public:
        IntArray ( size_t size = 10 , int ivalue = 0 );
        ...
      private:
        size_t size_;
        int *  data_;
    } ;
    
    IntArray::IntArray (size_t size, int ivalue) : size_(size) , data_(nullptr)
    {
      data_ = new int [size_];  // don't forget to check for failed allocation
      for (size_t i = 0; i  < size_; ++i)
        data_[i] = ivalue;
    }
    

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