Search code examples
c++pointersconstructorvirtualownership

Ownership issues when dealing with abstract base classes as members


When passing classes as arguments in constructors I end up passing pointers in most cases. The main reason for that is I have to pass abstract classes that cannot be instantiated, and as a reference cannot be null I do not really have a choice...

Here is an example :

// Abstract class A
class A { 
    virtual void foo() = 0;
};

class B : public A {
    void foo();
};

class C {
public:
    C(A* a) : _a(a) {};
private:
    A* _a;
};

In some cases I want C to take care of the A object _a is pointing at (delete it when deleted), in other cases I want C to delete _a without deleting the A object.

What are the best practices to have a sound programming methodology ?


Solution

  • Use shared_ptr to express shared ownership, and unique_ptr to express unique ownership. If you are sure that the lifetime of C is bounded by the lifetime of the A object (or another object owning A) then you can use a reference, or a shared_ptr with a nil deleter.