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!
If
BaseEventPtris a smart pointer it should be OK.Basically the shared pointer calls
deleteon the real pointer when there are no more references. If the base class has a virtual destructor defined,deletecalls the proper subclass’ destructor.For example:
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).