Search code examples
c++inheritancemake-shared

Using boost::make_shared with inheritence


Consider two classes

class A{
public:
    int i;
    A(){}
    explicit A(const int ii):i(ii){}
    virtual ~A(){
        cout<<"~A - "<< i <<endl;
    }
    virtual void inc(){
        i++;
        cout<<"i: "<<i<<endl;
    }
};

class B: public A{
public:
    int j;
    B(){}
    explicit B(const int jj, const int ii=-1):A(ii), j(jj){}
    ~B(){
        cout<<"~B - "<<i<<", "<<j<<endl;
    }
    void inc(){
        A::inc();
        j++;
        cout<<"j: "<<j<<endl;
    }
};

Now we can do like this in main():

A *pa = new B();
//...
pa->inc(); // implements B::inc();

Now the version using boost library

boost::shared_ptr<A> pa = boost::make_shared<B>(2);
//...
pa->inc(); // implements B::inc();

My question, in using the boost version, is whether it's fine to use this way, i.e., both versions can be used in same manner, or do I need to do something extra (I don't know much internals of boost)


Solution

  • There are a couple of things you can't do with smart pointers:

    • You can't pass a smart pointer as argument to a function which expects a normal pointer.
    • You can't assign a normal pointer to a smart pointer.

    Other that that you can handle a smart pointer as any other pointer, including calling virtual functions and the correct thing will happen.

    PS. If possible, I recommend you to migrate to the C++11 smart pointers instead. They were "inspired" (i.e. more or less copied straight) by the Boost smart pointers, so all you really have to do is include the <memory> header file and change e.g. boost::shared_ptr to std::shared_ptr. See e.g. this reference site.