By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,064 Members | 1,388 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,064 IT Pros & Developers. It's quick & easy.

Multiple objects from one definition line?

P: 88
It is possible to make many objects from one declaration line? Like:
Expand|Select|Wrap|Line Numbers
  1.  
  2. String objName = "";
  3.  
  4. for(int i = 0; i < 10, i++)
  5. {
  6.   Object objName;      //Define an object with the value of objName
  7.   objName = objName+i; //Change objName to make different objects
  8. }
  9.  
  10.  
Nov 19 '15 #1
Share this Question
Share on Google+
3 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
Use an array.

Expand|Select|Wrap|Line Numbers
  1. Object array[10];   //10 objects of type array.
This only works when you can use the class default constructor.

This assumes you are in C++. The code sample you posted looks like C#.
Nov 19 '15 #2

P: 88
ok, I see. Thanks man. Is it possible to get the user to set the number of objects? like:

Expand|Select|Wrap|Line Numbers
  1.  
  2. int input = Input.getUserInput();
  3. Object array[input];
  4.  
  5.  
Nov 20 '15 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
Yes. In this case you create the array on the heap using the new operator.

The caveat is that since you allocated the memory, you are responsible for deleting the objects. If you don't you have a memory leak. Now you need to pay attention to destructors.

Expand|Select|Wrap|Line Numbers
  1. int num = 0;
  2. cout << "Enter number of array elements: ";
  3. cin >> num;
  4.  
  5. Object* array = new Object[num];
And if you are in C++ you would use a vector<Object> instead of reinventing array coding techniques.
Nov 20 '15 #4

Post your reply

Sign in to post your reply or Sign up for a free account.