• Advertisement
Sign in to follow this  

Storing abstract objects

This topic is 3622 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi All, Is it possible to store a list of abstract objetcs. For example if i wanted to store a list of vehicles which could consist of cars trucks etc...
public class vehicle        // Abstract class
{
void draw() = 0; 
}

public class car : public vehicle
{
}

puclic class truc : public vehicle
{
}
Assuming the above, ideally i would like to store a list which can be added to at any point. I was thinking of using a vector stl but cant as cannot instantiate an abstract class
vector<vehicle> vehicleList;
Is there an alternative to doing this? Cheers

Share this post


Link to post
Share on other sites
Advertisement
Use:


std::vector< vehicle* > m_Vehicles.


You can't instantiate an abstract class because draw has no implementation within vehicle. With the above you create your classes as you have but you have to store pointers to them.

Share this post


Link to post
Share on other sites
The problem is that vector tries to store actual instances of vehicle. Even if it wasn't an abstract class, you wouldn't be able to store it's derived classes car, truck, plane, etc. within the vector.

You have a few possible solutions available to you.

1) Store pointers and allocate on the heap.
Cons: Lots of manual memory management.

2) Store smart pointers such as shared_ptr and allocate on the heap.
Cons: Still minor overhead from reference counting and heap allocation.

3) Use one of boost's pointer containers.
Cons: Still minor overhead from heap allocation.

4) Use boost::variant
Cons: Need to know about the subclasses you're using ahead of time.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement