Storing abstract objects

Started by
3 comments, last by MaulingMonkey 16 years, 2 months ago
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
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.
Or boost::ptr_vector<>. Or std::vector< boost::shared_ptr<> >.
Cheers guys, i knew itd be something simple i was missing. Thanks
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.

This topic is closed to new replies.

Advertisement