开发者

Storing a list of classes and specialising a function by sub-classing in C++?

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...


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.


The function must be virtual if you want polymorphism.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜