|
-
May 1st, 2005, 06:01 PM
#2
Re: Help with Vectors of Classes and Dervived Classes
 Originally Posted by d4m
Since all my objects are Components, can I make an vector of Components and use it for any type of Object which I have?
Nope. In C++ that won't work. It will compile and run, but what is actually stored in your vector will be copies of the CComponent part of your other classes. The objects will be sliced.
 Originally Posted by d4m
vector<CComponent> ComponentList
CPump NewPump
ComponentList.push_back(NewPump)
Is this something doable?
Yes it is, but not that way for the reason explained above. You need to store pointers to dynamically allocated objects instead.
Code:
vector<CComponent*> ComponentList
ComponentList.push_back(new CPump);
But now remember to delete the object before you remove it from the vector, or let the vector go out of scope.
Code:
delete ComponentList.back(); // Delete the last object
ComponentList.pop_back(); // remove the pointer to it from the vector
 Originally Posted by d4m
If I wanted to dynamically allocate Components while the program is running, do I have to allocate the Component dynamically, or is that handled within the vector when I push_back?
All memory allocation of the object type you store will be handled by the vector. It will not though handle memory pointed to by pointers you store in it. (hence the delete above is needed)
Insert entertaining phrase here
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|