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

dynamic array of objects in C++

P: 4
If I have these classes:

Expand|Select|Wrap|Line Numbers
  1. class student {
  2. private: 
  3. string * name;
  4. int faculty number;
  5. date datebirth;
  6. public:
  7. ...
  8. };
  10. class students : public student {
  11. private:
  12. /*array with objects from class student  -  how to define it ? */
  13. int stream;
  14. string *specialty;
  15. public:
  16. void AddNew(student student1);  /* with dynamic array */
  17. void DeleteStudent(string *name); 
  18. };
how can i write a method to add a object in a dynamic array ?
Jun 4 '07 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 1,764
If I have these classes:

class student {
string * name;
int faculty number;
date datebirth;

class students : public student {
/*array with objects from class student - how to define it ? */
int stream;
string *specialty;
void AddNew(student student1); /* with dynamic array */
void DeleteStudent(string *name);

how can i write a method to add a object in a dynamic array ?
/*array with objects from class student - how to define it ? */,I'm not quite sure that i understand u well,can u rephrase ur question?

how can i write a method to add a object in a dynamic array ?

U will need to find current number of elements in ur dynamic array,and increase it for one.

void AddNew(student student1,student *array);

and then:

array=new array[((sizeof(array)/sizeof(student))+1]

Jun 4 '07 #2

Expert Mod 5K+
P: 9,197
The problem with using an array is that it is fixed in size. If your students class has a dynamic array, then the array has to be created to a given size.

Once you do that, you have to keep track of how many student objects are in the array. AND when the array fills up, you have to create a bigger array and copy the old array to the new array and then delete the old array.

Pant. Pant. Pant.

C++ implements a container called vector that implements your array and keeps track of all that stuff about how many students are in the array and to expand the array if needed.

All you have to do is create a student and add it to the vector:

Expand|Select|Wrap|Line Numbers
  1. student s(...all of the constructor arguments...);
  3. vector<student> students;
  5. students.push_back(s);
and you are done.

If you have to use your own array, be prepared for substantial code that essentially duplicates the code for the vector.
Jun 4 '07 #3

Post your reply

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