Search code examples
c++pointerssharedradixderived

Returning new base class when the parent class shared pointer is the return type


Can you have a parent class shared pointer return type of a function and then return a new child class without it being a shared pointer? I'm not sure how shared pointers work in these situations, do they act like a regular pointer? Here is my example:

BaseEventPtr Actions::getEvent(const std::string& nodeName)
{
    if(asLowerCaseString(nodeName) == "action")
        return new ActionEvent(&m_interface);

    return nullptr;
}

ActionEvent is the subclass of BaseEvent in this situation.

Cheers!


Solution

  • If BaseEventPtr is a smart pointer it should be OK.

    Basically the shared pointer calls delete on the real pointer when there are no more references. If the base class has a virtual destructor defined, delete calls the proper subclass' destructor.

    For example:

    class NonVirtualBase {};
    class NonVirtualSubclass: public NonVirtualBase {};
    
    shared_ptr<NonVirtualBase> ptr( new NonVirtualSubclass() ); // NOT OK!
    
    class VirtualBase
    {
        virtual ~VirtualBase() {}
    };
    
    class VirtualSubclass: public VirtualBase {};
    
    shared_ptr<VirtualBase> ptr( new VirtualSubclass() ); // OK
    

    This applies to normal (naked) pointers as well. That's why as a general rule, if a class may serve as a base class in the future, it should be defined with a virtual destructor (even if empty).