Nathan Almeida
Nathan Almeida

Reputation: 199

How to return an Array of Objects from a function

This simple object return works fine.

Bubbles& Foo() {
  static Bubbles foo(10);
  foo.print();
  return foo;
}

int main() {

  Bubbles *bar;
  bar = &Foo();

  bar->print();

  printf("Program Ends");
  return 0;
}

Now I need to know how to return an Array of Objects! I have 0 idea on how I should declare it

All I know is:

Bubbles& createBubbles() {
 static Bubbles *BubblesArray[arrayNumber];
 for (int i = 0; i < arrayNumber; i++) {
    BubblesArray[i] = new Bubbles(i);
    BubblesArray[i]->print();

  }

  return BubblesArray;
}

seems to create an array of Objects the way I need.
So how can I return this array so I can use it outside the function?

Upvotes: 0

Views: 172

Answers (2)

walnut
walnut

Reputation: 22152

You can get the same behavior as in your first example. You just have to specify the type correctly:

using BubblesArrayType = Bubbles*[arrayNumber];

BubblesArrayType& createBubbles() {
  static BubblesArrayType BubblesArray;
  //...
  return BubblesArray;
}

or you can let type deduction figure the type out for you:

auto& createBubbles() {
  static Bubbles *BubblesArray[arrayNumber];
  //...
  return BubblesArray;
}

But as mentioned in comments and other answers, this is unlikely to be a good design and style. Without further information it is not really clear though, why you are using static and return-by-reference in the first place.

Upvotes: 1

TuanDT
TuanDT

Reputation: 1667

Your return type expects only 1 Bubbles object. If you want to return an array, you have to change the function return type. I would strongly recommend not playing with raw array and stick with the std library. Using C++11 (DISCLAIMER: CODE UNTESTED) will look something along the line of:

std::vector<Bubbles> createBubbles(const int& arrayNumber) {
 std::vector<Bubbles> bubblesVector;
 for (int i = 0; i < arrayNumber; i++) {
    bubblesVector.push_back(Bubbles(i));
    bubblesVector[i].print();    
  }    
  return bubblesVector;
}

Note that this assume your Bubbles object has appropriate default/copy/move constructor, destructor, assignment operator...

Simple return type std::vector<Bubbles> can take advantage of copy-elision which is extremely efficient.

Upvotes: 1

Related Questions