开发者

Can boost::smart_ptr be used in polymorphism?

开发者 https://www.devze.com 2023-02-05 20:48 出处:网络
Can boost::smart_ptr such as scoped_ptr and s开发者_JS百科hared_ptr be used in polymorphism? class SomeClass

Can boost::smart_ptr such as scoped_ptr and s开发者_JS百科hared_ptr be used in polymorphism?

class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}


I believe the answer is yes; boost pointers are coded such that derived classes are accepted wherever a superclass would be.


Yes:

#include <string>
#include <iostream>
using namespace std;
#include <boost\shared_ptr.hpp>
using namespace boost;


class Foo
{
public:
    virtual string speak() const { return "Foo"; }
    virtual ~Foo() {};
};

class Bar : public Foo
{
public:
    string speak() const { return "Bar"; }
};

int main()
{
    boost::shared_ptr<Foo> my_foo(new Bar);
    cout << my_foo->speak();
}

Output is: Bar

0

精彩评论

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