Variable Sized Object May Not Be Initialized

I'm pretty new to classes and I'm trying to store data into each bunny created (Name, Age) But for some reason when I try to do
std::string NameBunny[i] = Random.FirstName(); It gets the error:
"Variable sized object may not be initialized"
Help? (Code made on an android ide do may be messy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <time.h>

void DayOne();

constexpr int BunnyStart = 5;

class RandomizeDetails{
	
	public:
	
	std::string FirstName(){
		std::string NameArray[] = {"Thumper","Oreo","Coco","Snowball","Marshmello","Bugzy","Midnight"};
		int Random = rand() % 7;
		std::string TheName = NameArray[Random];
		return TheName;
	}
	int Age(){
		int AgeArray[] = {0,1,2,3,4,5,6,7,8,9};
		int Random = rand() % 10;
		int TheAge = AgeArray[Random];
		return TheAge;
	}
};


int main(){
	srand(time(0));
	DayOne();
}

void DayOne(){
	RandomizeDetails  Random;
	
	for(int i = 0; i < BunnyStart; i++){
		std::string NameBunny[i] = Random.FirstName();
		
		std::cout << "Name: " << NameBunny[i] << std::endl;
		std::cout << "Age: " << Random.Age() << "\n\n";
	}
}
Last edited on
std::string NameBunny[i] = Random.FirstName();

This isn't doing what you think its doing from a syntax point of view.
It thinks you're declaring a VLA (Variable-Length Array) of size i on line 37 (which is illegal in C++ anyway).

No need for an array in DayOne, just make a string.

1
2
3
4
5
6
	for(int i = 0; i < BunnyStart; i++){
		std::string NameBunny = Random.FirstName();
		
		std::cout << "Name: " << NameBunny << std::endl;
		std::cout << "Age: " << Random.Age() << "\n\n";
	}

or just

1
2
3
4
	for(int i = 0; i < BunnyStart; i++){
		std::cout << "Name: " << Random.FirstName() << std::endl;
		std::cout << "Age: " << Random.Age() << "\n\n";
	}


Edit: If you actually want an array, declare it like this, before the for loop.
std::string NameBunny[BunnyStart];
Last edited on
Alright, but I need a way to somehow make a system that automatically creates variables for the bunnys with different traits
You want bunnies?
std::vector<Bunny> horde( 42 );
Done!

The only thing you need is a class/struct Bunny, whose default constructor sets the name and age of that bunny the way you want.

1
2
3
4
5
6
7
8
struct Bunny {
  size_t age;
  std::string name;
  Bunny()
  : age( Age() )
    name( FirstName() )
  {}
};

(Alas, your functions cannot be called exactly like that. Close though.)
Thanks!
Topic archived. No new replies allowed.