Take a look at this code:
Foo &Bar::Copy()
{
return Bar();
}
The class Bar is inherited from Foo, and Foo is an abstract class. But when I call Bar() and return it, is it safe to do so? Or would I be returning the address of a local variable that would be freed by the end of the Copy() function?
Advice is greatly appreciated!
When calling
Bar();you call constructor on an implicit temporary object to which reference is returned. If you intend to create aClone()like function a typical solution is to create the clone on the heap withnew. You may use a kind of smart pointer to simplify life cycle management. You may also apply covariant return type to avoid type conversions in some cases using signature:Bar &Bar::Copy()