1

I need to return an array of class objects from a function. I understand from research that the best way to do this is with a pointer, but is this the best way given my program design, and the need to access this from multiple CPP files?

main.cpp

#include <class.h>
#include <functions.h>

int main(){
Class Object[2][]; //define second dimension here?
some_function(); //should return / create the array with filled in elements.
int var = arr[2][3]; // want to be able to do something like this in main
}

functions.cpp

void some_function(){
// assign values
arr[2][3] = 1;
}
1
  • 1
    Try a vector. vector<vector<int>> some_function() {...} Of course you'll need C++11 to use <int>> and not <int> >. Commented Apr 16, 2012 at 22:16

1 Answer 1

8

You should really use std::vector<std::vector<Object> > for your multi-dimensional array. Using raw arrays is error prone, and since you're using C++ anyways, why not make use of something as useful as the std::vector which automatically resizes when needed.

You can even return the vector from your function like so:

std::vector<std::vector<Object> > my_function() { /* do something */ return some_vector; }

Sign up to request clarification or add additional context in comments.

4 Comments

And if you are using C++11 and Object is moveable this is also optimal (in that you don't copy everything in the vectors). If you aren't using C++11 maybe put your objects into boost or tr1 shared_ptr.
Does returning a vector like this, with no pointer, enable the vector array to be returned without any bulk data copying?
@MartinJames given a decent compiler, yes.
@Martin: yes, look up Return Value Optimization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.