-4

I want to create multiple global instances of a class. I tried to do this:

for (int x = 0; x <= 10; x++) {

            bunny x;
            x.create(5, 5); 

            x.printCreate(); 
        }

(The class name is bunny)

What I tried to do here, was to create an instance named the value that x is at the time, then use the variable x to do functions on the instance with the name the value of x.

But what was brought to my attention was that it just created an instance named num each time, and destroyed it once the loop was over. (I'm pretty new to this, so please bear with me, and the functions I've called from the class have random functions and stuff in them, this fooled me into thinking that it was indeed creating 10 different instances.)

How can I do this, so that 10 global instances are made (so they are not destroyed once the loop is over), and each instance is numbered from 1 - 10. If, like variables, the instance name can't begin with a number, then something like: a1, a2, a3, a4....

This has confused me for so long, Thanks for any help.

1 Answers1

1

You could create a class instance by doing this-

bunny x;

And if you want to create multiple instances, you could do it as a normal variable declaration

bunny x, y, z;

or as an array of instances

bunny x[10];

Then you may use the above-mentioned functions as follows-

  1. If you declared the instances using bunny x, y, z; then you could call them one by one (x.create(5, 5); x.printCreate(5, 5);) and so on.

  2. If you declared the instances as an array of instances then do it using a for-loop like this-

    for (int i = 0; i <= 10; i++) {
    
        x[i].create(5, 5); 
    
        x[i].printCreate(); 
    
    }
    
aravind
  • 130
  • 1
  • 11
  • Thank you so much! Finally, an answer that makes sense to me! I could just do this with the array method that you mentioned... although, I'm curious, is it possible for me to create multiple instances without using arrays and defining each one? Like I have tried to do in my question? Thanks for the help once again :) – thisisnotworking4meplshelp Apr 17 '18 at 11:55
  • Yes, you could. That would be dynamic memory allocation. And for that, you would have to create each instance in each iteration like you did and store their pointers somewhere. I believe its better if you just stick to this if you know the actual number of instances that you would actually need. – aravind Apr 18 '18 at 06:13