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?
std::arrayorstd::vectorand this becomes trivial. Otherwise it's not happening unless you pass the array as an output parameter.BubblesArrayis a pointer to the start of an array. Hence you want the return type to beBubbles*i.e.Bubbles* createBubbles(), then the return statement makes sense. Note that you using a static variable won't play nice with multi-threading and there's a lot of memory leak in the code. Consider using std:: functions and classes such as std::vector and std::unique_ptr or std::shared_ptr.static? This is, except in narrow circumstances, a bad design. If you added an explanation of why you think that is necessary, then we could probably suggest a better approach.