Adam Lee
Adam Lee

Reputation: 25768

why does a clone method always return a pointer?

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

Answers (1)

Cornstalks
Cornstalks

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

Related Questions