Download MetaTrader 5

value type vs. reference type in MQL5

To add comments, please log in or register
brantheman
5
brantheman  

I have some basic questions on the MQL5 language:

1. Classes that I define are automatically passed by reference?

2. Arrays are automatically passed by reference?

3. Returning a class from a method returns it by reference?

4. How do I declare a new class instance inside a method when I intend to return that instance from the method? Is that possible in MQL5? (I tried returning pointers and it seems even those go out of scope at the end of the method.)

5. Suppose I have a private member of a class that is a separate class type, is that variable initialized to an instance of that object? And if I reassign it, does it do a full memcpy?

Example:

class A { public: double Data[]; };

class B {

  protected: A _a1, _a2; // these are pointing to valid data when the object is constructed, right?

  public: void Construct(A a1, A &a2){

    _a1 = a1; // did we just make a copy? was A1 a copy coming in?

    _a2 = a2; // same questions...

};

Alexey Da
Moderator
6636
Alexey Da  

Have you read MQL5 Reference?

  1. Objects of classes should be passed into function as reference (https://www.mql5.com/en/docs/basis/function/parameterpass)
  2. Arrays should be passed into function as reference (https://www.mql5.com/en/docs/basis/function/parameterpass)
  3. Yes (https://www.mql5.com/en/docs/basis/operators/return)
  4. Create object's instance using operator new and then return a pointer (https://www.mql5.com/en/docs/basis/operators/newoperator)
  5. In your example you can't. You should implement your own copy function.

I strongly recommend you to read MQL5 Reference at first.

Documentation on MQL5: Language Basics / Functions / Passing Parameters
  • www.mql5.com
Language Basics / Functions / Passing Parameters - Documentation on MQL5
To add comments, please log in or register