First, your code is not valid C++. Declaring empty arrays using []
does not exist in C++.
So the first thing is to turn this into valid C++ that still preserves what you’re trying to accomplish. One solution is to use std::vector
:
#include <vector>
class Universe {
public:
std::vector<Star> stars;
std::vector<Planet> planets;
public:
Universe(const std::vector<Star>& st,
const std::vector<Planet>& pl) : stars(st), planets(pl) {}
};
Note the replacement of the non-C++ code with std::vector
. Also note that we initialize the vectors using the initializer-list
.
Last, note that we no longer need to keep the sizes as separate member variables. Why? Because a vector knows its size by calling the vector::size()
member function. For example:
for(int i = 0;i < starsLength;i++) {
can be replaced with
for(int i = 0;i < stars.size();i++) {
In your buildUniverse
function, use the following changes:
Universe buildUniverse(int size, int seed) {
Point bounds = Point{static_cast <float> (size),static_cast <float> (size)}; //0,0 to size,size
int starCount = min(size/10,random(size/5));
int planetCount = min(size/3,random(size));
std::vector<Star> stars(starCount);
std::vector<Planet> planets(planetCount);
//...
Universe uni(stars, planets);
The rest of the code stays the same. Now, if after the call to create the Universe
, you see that the vectors didn’t pass the correct information, then look further. The code above conforms to “normal” C++, such that we can go further and figure out the issue.
2
solved Array data is ‘lost’ after passing the array to another object