Returning a new base class when the parent class is a return type

Is it possible to use the return type of the parent class for the return type of the function, and then return a new child class without being a common pointer? I'm not sure how generic 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; } 

An ActionEvent is a subclass of BaseEvent in this situation.

Hooray!

+4
source share
1 answer

If BaseEventPtr is a smart pointer, it should be fine.

Basically, a generic pointer calls delete on a real pointer when there are no more links. If the base class has a virtual destructor , delete invokes the corresponding subclass destructor.

For instance:

 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 also applies to regular (bare) pointers. That is why, as a rule, if a class can serve as a base class in the future, it must be defined with a virtual destructor (even if empty).

+2
source

Source: https://habr.com/ru/post/1439425/


All Articles