Search code examples
c++boostinitializationshared-ptrmember

Creating a const share_ptr<pure_virtual_class> member


I have a number of classes that derive from a pure virtal base:

class base {
public:
    virtual int f() = 0;
};

class derived_0 : public base {
public:
    int f() {return 0;}
};

class derived_1 : public base {
public:
    int f() {return 1;}
};

I only put two derived classes for brevity, but in practice I have more.

And I would like to create a class that has a const shared pointer to the base. I would like do to the following but I can't as I must initialize the const pointer in the initialization list:

class C{
public:
    C(bool type) { 
        if(type) {
            derived_0* xx = new derived_0;
            x = shared_ptr<base>( xx );
        }
        else {
            derived_1* xx = new derived1;
            x = shared_ptr<base>( xx );
        }
    } 
private:
    const share_ptr<base> x;
};

How can I get this functionality?


Solution

  • You encapsulate the creation of the object in a function, like this:

    shared_ptr<base> create_base(bool type) {
         if(type) {
             return make_shared<derived_0>();
         }
         else {
             return make_shared<derived_1>();
         }
    }
    

    And then you can use it in your initialization-list:

    class C{
    public:
        C(bool type)
        : x(create_base(type))
        {}
    private:
        const share_ptr<base> x;
    };