Dan
Dan

Reputation: 35453

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

Upvotes: 0

Views: 155

Answers (3)

Naveen
Naveen

Reputation: 73443

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.

Upvotes: 0

rlbond
rlbond

Reputation: 67789

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.

Upvotes: 8

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43130

The function must be virtual if you want polymorphism.

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

Upvotes: 2

Related Questions