Passing a dynamic object array via reference

 

Hello everyone,

I want to pass a dynamic object array via reference to another class. Here is an example how I tried it:

void Class1
{
        MyObject *objectArray[];

	// ... do fancy stuff with array

	Class2 class2 = new Class2();
	class2.Create(objectArray);
}

void Class2
{
        MyObject *anotherObjectArray[];

        void Create(MyObject & objectArray[])
        {
        	anotherObjectArray = objectArray;
        }       
}

First error I get in Class1: 'Create' - no one of the overloads can be applied to the function call 

- It seems that the parameter assignment isn't correct

Second error I get in Class2 when I try to assign the parameter array to the local array: invalid array access.

- So how can I assign an array reference to a local reference?


How can I pass a dynamic object array to another class by reference? I don't get it...

 

You need to remove the stars like this

MyObject objectArray[];
class2.Create(objectArray);

and arrays need to be copied with ArrayCopy().

 

Hi, 

without stars it seems to work at first glance. Thanks for that.


But ArrayCopy throws an error: structures containing objects are not allowed

I think the problem is that it's an array of objects!?


 

ArrayCopy works with simple structures only, but you can achieve the same with a loop. Try this:

void CopyMyObjects(MyObject* &arr1[], MyObject* &arr2[])
{
   ArrayResize(arr1,ArraySize(arr2));
   for(int i=0; i<ArraySize(arr2); i++) arr1[i]=arr2[i];
}

void Class1
{
   MyObject *objectArray[];
   Class2 class2 = new Class2();
   class2.Create(objectArray);
}

void Class2
{
   MyObject *anotherObjectArray[];
   void Create(MyObject* &objectArray[])
    {
      CopyMyObjects(anotherObjectArray,objectArray);
    }       
}
 
You wouldn't use arrays, rather, you'd use vector like MQL collections. 
#include <arrays/arrayobj.mqh>


template <typename T>
class ObjVector : public CArrayObj {
   public: T operator[](int i) {
      return this.At(i);
   }
};


class Foo : public CObject {};


class Bar : public CObject {
protected:
   ObjVector<Foo*>   *m_foos;
public:
   Bar(ObjVector<Foo*> *foos):m_foos(foos){}
   ~Bar() {
      if (CheckPointer(m_foos) == POINTER_DYNAMIC)
         delete m_foos;
   }
};



void OnStart() {
   ObjVector<Foo*> *foos = new ObjVector<Foo*>();
   
   for (int i=0; i<10; i++) {
      foos.Add(new Foo());
   }
   
   Bar bar(foos);   
}
 

Hi folks,


thanks for your answers. I'll try both. ArrayObject doesn't look easy as well, but maybe it fits better. 

Normally I'm a C# developer so I kinda feel like I'm in a time machine back to the 80's with this pointer handling. :D

Reason: