views:

89

answers:

3

I'm trying to subclass a class with a specialisation of how I want a particular function to be performed. However, C++ implicitly converts my class to its base class when I store it in a list. Clearly the list could store any subclass of the class, so this is acceptable, but how would I go about storing the class so I can access this particular function.

The only way I can think of doing this is to use templates, are there any other options?

Here is an example:

class A
{
    A() {}
    virtual void function()
    {
    }
}

class B : public A
{
    B() {}
    void function()
    {
    }
}

boost::shared_ptr<B> b = boost::shared_ptr<B>(new b);
std::list<boost::shared_ptr<A> > objects;
objects.push_back(b);

// pull t out of objects

t.function();

Edit: Oversimplified this, so I've fixed a few things...

+2  A: 

The function must be virtual if you want polymorphism.

class A
{
    A() {}
    virtual void function()
    {
    }
}
Nick D
+8  A: 

This is a phenomenon called slicing. The answer is to store a container of pointers instead, such as std::list<A*>. Just remember to delete everything when you're done.

If you can use the Boost libraries, there is a great library called Pointer Container which helps with this procedure.

rlbond
A: 

As others suggested the function should be virtual. To store it in a list you need to store them as pointers (either raw or with boost wrappers). So that when you invoke the function using the pointer the polymorphism comes into picture and correct function gets executed.

Naveen