Boost logo

Boost Users :

Subject: [Boost-users] Up-casting shared_ptr
From: david.weber_at_[hidden]
Date: 2008-11-18 11:30:28


We're using smart pointers, and due to the way that they are created, we
wish to hide the functionality behind a static create() function for
each class. That way, the callers only need call create() and they have
a smart_pointer to a new object, without having to worry too much about
implementation details.

So, this has been working fine, until I tried doing some polymorphism.
Basically, we have a smart pointer to a base class, where the derived
class is chosen at run time, (based on what the caller wants to do).
The base class is pure virtual, so we don't know, (or care to know) how
the child class implements its functionality. The following code
illustrates what I'm trying to do:

#include <iostream>
#include <boost/shared_ptr.hpp>

// Base class
class base
{
public:
    typedef boost::shared_ptr<base> SharedPtr;
    
    ~base(){};
    virtual void foo(){ std::cout << "base" << std::endl;};

    static SharedPtr create(){ return SharedPtr(new base); };

protected:
    base(){};
};

// Derived class
class d1 : base
{
public:
    typedef boost::shared_ptr<d1> SharedPtr;

    ~d1(){};
    void foo() {std::cout << "derived 1" << std::endl;};
    
    static SharedPtr create() { return SharedPtr(new d1); };

protected:
    d1(){};
};

int main()
{
    base::SharedPtr bsp;

    d1::SharedPtr d1sp = d1::create();
    d1sp->foo();

    // This is producing the error. I want to upcast my d1::SharedPtr
to a
    // base::SharedPtr, so that it can be stored, and the reference
count
    // is still intact
    bsp = boost::static_pointer_cast<base>(d1sp);
}

And here is the error that I'm getting (from Visual Studio 2003)

c:\Program Files\boost\boost_1_35_0\boost\shared_ptr.hpp(222) : error
C2243: 'static_cast' : conversion from 'd1 *const' to
'boost::shared_ptr<T>::element_type * with [T=base]' exists, but is
inaccessible; c:\Program
Files\boost\boost_1_35_0\boost\shared_ptr.hpp(513) : see reference to
function template instantiation
'boost::shared_ptr<T>::shared_ptr<d1>(const boost::shared_ptr<d1>
&,boost::detail::static_cast_tag) with [T=base]' being compiled;
c:\Documents and Settings\td26134\Desktop\trunk1\main.cpp(54) : see
reference to function template instantiation 'boost::shared_ptr<T>
boost::static_pointer_cast<base,d1>(const boost::shared_ptr<d1> &) with
[T=base]' being compiled

Thanks..

--dw



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net