Object Create Operator new

Overview

The new operator creates an object of the appropriate size, invokes its constructor, and returns a descriptor for the created object. If the creation fails, it returns a null descriptor, which can be compared with the NULL constant.

Usage Constraints

  • Applicable only to class objects.
  • Cannot be applied to structures.
  • Should not be used for creating arrays of objects; use ArrayResize() for arrays.
  • Return Value

  • A descriptor of the created object.
  • NULL constant if creation fails.
  • Object Lifetime

    Objects created with the new operator must be explicitly removed using the delete operator.

    Related Concepts

  • [Object descriptor is not a memory address pointer.](https://docs.mql4.com/en/basis/operators/newoperator#note)
  • [Initialization of Variables](/basis/variables/initialization)
  • [Visibility Scope and Lifetime of Variables](/basis/variables/variable_scope)
  • [Creating and Deleting Objects](/basis/variables/object_live)
  • [Object Delete Operator delete](/basis/operators/deleteoperator)
  • Example

    void CTetrisField::NewShape()
      {
       m_ypos=HORZ_BORDER;
    //--- randomly create one of the 7 possible shapes
       int nshape=rand()%7;
       switch(nshape)
         {
          case 0: m_shape=new CTetrisShape1; break;
          case 1: m_shape=new CTetrisShape2; break;
          case 2: m_shape=new CTetrisShape3; break;
          case 3: m_shape=new CTetrisShape4; break;
          case 4: m_shape=new CTetrisShape5; break;
          case 5: m_shape=new CTetrisShape6; break;
          case 6: m_shape=new CTetrisShape7; break;
         }
    //--- draw
       if(m_shape!=NULL)
         {
          //--- pre-settings
          m_shape.SetRightBorder(WIDTH_IN_PIXELS+VERT_BORDER);
          m_shape.SetYPos(m_ypos);
          m_shape.SetXPos(VERT_BORDER+SHAPE_SIZE*8);
          //--- draw
          m_shape.Draw();
         }
    //--- 
      }