Skip to content

Cloning an object through a base pointer

Question

You hold a base-class pointer to an object whose concrete derived type you do not know. How can you make a copy of it?

Short answer

Give the base class a virtual clone() (the virtual constructor idiom). Each derived class overrides it to return new Derived(*this) (or a smart pointer), so the call dispatches to the right copy constructor at run time. Covariant return types let overrides return the derived pointer type.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.6, p.226; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question

Start with a free lesson: Basic Statistics and Regression is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.

Read it free