MQL5: Using Keyword ‘this’

In MQL5, the keyword ‘this’ refers to the current instance of an object within a class. It allows you to access members and methods of the current object. When you’re working with object-oriented programming in MQL5, you often need to differentiate between the current instance and other instances of the same class. Here’s a brief overview of how ‘this’ is used:

  1. Accessing Object Members: You can use ‘this’ to access member variables and methods within the current object. For example:
class MyClass {
    int myVariable;

    void SetVariable(int value) {
        this.myVariable = value;
    }

    int GetVariable() {
        return this.myVariable;
    }
}

In the above example, ‘this.myVariable’ refers to the member variable ‘myVariable’ of the current instance of MyClass.

  1. Passing Object References: ‘this’ can also be used to pass a reference to the current object as a parameter to methods or functions. This is useful when you need to pass the current object to another function or method. For example:
class MyClass {
    void SomeMethod() {
        AnotherMethod(this);
    }

    void AnotherMethod(MyClass& obj) {
        // Do something with obj
    }
}

Here, ‘this’ is passed as a reference to the AnotherMethod function, allowing it to operate on the current object.

  1. Constructor Initialization: In constructors, ‘this’ is used to differentiate between parameters with the same name as member variables. For example:
class MyClass {
    int myVariable;

    MyClass(int myVariable) {
        this.myVariable = myVariable;
    }
}

In this case, ‘this.myVariable’ refers to the member variable ‘myVariable’, while ‘myVariable’ refers to the parameter passed to the constructor.

Overall, ‘this’ is a crucial keyword in MQL5 for working with object-oriented programming, allowing you to interact with the current instance of a class effectively.