Boost logo

Boost :

From: David B. Held (dheld_at_[hidden])
Date: 2002-03-24 13:41:20


I have something like this:

class Base
{
public:
    virtual void foo();
};

class Derived
{
public:
    virtual void foo();
    void bar();
};

typedef boost::shared_ptr<Base> PBase;
typedef boost::shared_ptr<Derived> PDerived;

std::vector<PBase> BaseObjs;
std::vector<PDerived> DerivedObjs;

I need DerivedObjs so I can call Derived::bar() without having
to do type checking and casting, but all Deriveds will go into
both BaseObjs and DerivedObjs, so I can call foo()
polymorphically. Here was my first attempt:

PDerived p(new Derived());

BaseObjs.push_back(p);
DerivedObjs.push_back(p);

Unfortunately, this didn't let me call foo() polymorphically from
BaseObjs. I guess when it converted from PBase to PDerived,
the underlying pointer lost the information that it was actually a
Derived*. I don't know. So I tried this:

Derived* p = new Derived();

BaseObjs.push_back(PBase(p));
DerivedObjs.push_back(PDerived(p));

This allows me to call foo() polymorphically, but, of course, fails
when everything gets cleaned up, since I passed ownership of
p to two different smart pointers. :( At this point, some advice
would be appreciated. ;)

Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk