MQL4 Documentation: Modifier '&' and Keyword 'this'

Passing Parameters by Reference

  • **Simple Types:** Can be passed by value or by reference.
  • **Compound Types (Arrays, Structures, Class Objects):** Always passed by reference.
  • **Reference Modifier (&):** Added before the parameter name in the function header to indicate passing by reference. Changes to the parameter inside the function affect the original variable.
  • **Preventing Modification:** Use the const modifier with & (e.g., const double &array[]) to prevent changes to parameters passed by reference.
  • **Arrays and Structures:** The & symbol is obligatory when passing arrays and structures as function parameters.
  • **Array Assignment:** Direct assignment of one array to another is not allowed; element-wise copying is required.
  • **Example:**

    class CDemoClass {
    private:
      double m_array[];
    public:
      void setArray(double &array[]);
    };

    void CDemoClass::setArray(double &array[]) { if(ArraySize(array) > 0) { ArrayResize(m_array, ArraySize(array)); ArrayCopy(m_array, array); } }

    Keyword this

  • **Purpose:** Provides a reference to the current object within its class or structure methods.
  • **Usage:** this always refers to the object whose method is being executed.
  • **Getting Object Pointer:** GetPointer(this) returns a pointer to the current object.
  • **Returning Object Pointers:** Functions can return object pointers using GetPointer(this) (e.g., CDemoClass *getDemoClass() { return(GetPointer(this)); }).
  • **Limitations:**
  • * Structures do not have pointers. * Operators new and delete cannot be applied to structures. * GetPointer(this) cannot be used within structure methods.

    **Example:**

    class CDemoClass {
    private:
      double m_array[];
    public:
      void setArray(double &array[]);
      CDemoClass *getDemoClass();
    };

    CDemoClass *CDemoClass::getDemoClass(void) { return(GetPointer(this)); }

    Related Topics

  • [Object Pointers](/basis/types/object_pointers)
  • [Creating and Deleting Objects](/basis/variables/object_live)
  • [Visibility Scope and Lifetime of Variables](/basis/variables/variable_scope)