Sign in to follow this  
TigerSam

Storing abstract objects

Recommended Posts

TigerSam    122
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
dave    2187
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
MaulingMonkey    1730
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this