George Todosi George Todosi - 15 days ago 8
C++ Question

C++ Returning a 2D array of objects from a function to use in another function

I've been working on a C++ project for school and I've encountered some problems when it comes to 2D arrays of objects. So I have the following class:

class mecanice
{
public:

mecanice();
~mecanice();
...
protected:

private:
...
MyClass Ob[8][8];
};


And I need a method that will return Ob so that I can use it in a method from some other class that will do stuff based on what's in Ob:

class doodle
{
public:
doodle();
~doodle();
void do_stuff(MyClass M[8][8]);
...
protected:

private:
...
};


I've tried all kinds ways of going about it but all of them ended up with compiling errors usually related to pointers. Is there any way to do this?

Answer

Try the following

const MyClass ( * myMagicMethod() )[8] const;

Or

typedef const MyClass ( *A )[8];

//...

A myMagicMethod() const;

The qualifier const is used if you do not want that the array would be changed in a method of other class.

Another approach is to pass the array by reference. For example

const MyClass ( & myMagicMethod() )[8][8] const;

Or

typedef MyClass ( &A )[8][8];

//...

const A myMagicMethod() const;

In the method that will process the array the parameter also must be declared like reference.

Comments