Reputation: 25768
I am reading some clone c++ implementation, it seems always define as
Clonable* clone();
I am wondering why always return a pointer; can I define a clone to return a Clonable object?
Upvotes: 2
Views: 161
Reputation: 38228
can I define a clone to return a
Clonable
object?
Sure. Heck, you could make a clone()
method that returns anything you want. My guess is that the Clonable
class is meant to be used polymorphically, and that the clone()
method is virtual
. Pointers (or references) are your only option for runtime polymorphism in C++. If it didn't return a pointer, you'd get object slicing.
Upvotes: 8