Posts Tagged ‘polymorphism’

C++: Polymorphic cloning and the CRTP (Curiously Recurring Template Pattern)

August 22, 2013 30 comments

A common problem in C++ occurs when you have an object of an unknown derived type and want to make a copy of it. Consider the following code:

class Vehicle {}

class Car : public Vehicle {}
class Plane : public Vehicle {}
class Train : public Vehicle {}

function make_a_copy(Vehicle *v)
  Vehicle *copy_of_vehicle = new ????(*v);

You can’t just useĀ new Vehicle in this situation because only the base class elements (those from theĀ Vehicle base class) will be available in the copy. So what do we do? Read more…

%d bloggers like this: