Copy Constructor - Script for MetaTrader 5 | Trading Script Download - MT4/MT5 Resources
The following is an option available for MQL.
This technique is called "copy constructor". Make sure to copy all fields recursively, including complex data types.
Please refer to the sample code below and you will understand how it works.
/************************************************************************/ Blank class example() { print ( __function__ ); a1; A a2=Fa(); //Receive object from function a1.work(); a1.Report(); //1 1 1 1 a2.Report(); //3 3 3 3 /*Continue to use the object in the function*/ a2.Work(); a2.Report(); //4 4 4 4 return ; } /************************************************************************ Category A parts*/ Structure C { integer MX; C():mx( 0 ) {}}; class D { people : integer MX; D():mx( 0 ) {} D(D &d):mx(d.mx) {}}; /********************************************************************/ class a { protected : Integer MX; //Simple integer horse[]; //Mass C mc; //Structure D d; //Class people : /*Copy constructor*/ A(A &a):mx(a.mx),d(ad) { Array copy (m, m); mc=a.mc;} /*Explicit default constructor*/ A():mx( 0 ){} /*method*/ blank work(){mx++; array resize (ma,mx); mc.mx=mx; d.mx=mx;} blank report() { print (mx, " " , array size (m), " " ,mc.mx, " " ,d.mx);} }; /************************************************************************/ Afa() { one by one; for ( integer i = 0 ; i < 3 ; i++) {a.job();} //many jobs return one; //return class object } /**/
Want to return a structure?
You can usually update a structure using a function as a parameter sent by reference.
If you wish to return a struct with a function, that's possible, but unlike classes, structs don't require an explicit copy constructor.
/************************************************************************/ Blank structure example() { print ( __function__ ); B b1; B b2=Fb(); //The structure receives b1.mx++ from the function ; /**/ Print (b1.mx, ” “ , array size (b1.ma)); // 1 0 print (b2.mx, ” “ , array size (b2.ma)); // 10 9 return ; } /************************************************************************/ Structure B { integer MX; integer horse[]; B():mx( 0 ){} //Constructor, officially not needed }; /**************************************************************************/ BFB() { b; for ( integer i = 0 ; i < 10 ; i++) {b.mx++; Array resize (b.ma,i);} //Hard work returns B; //Structure returns } /**/
Attachment download
📎 copyconstructor.mq5 (5.52 KB)
Source: MQL5 #29357
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •