If I want to clone a polymorphic object in C ++ (i.e. an instance of class A that is derived from some other class B), the easiest way seems to give B a virtual clone function that needs to be redefined by A and looks like that:
A* clone(){ return new A(*this); }
My problem is that I find this unnecessary boilerplate code as it is almost always necessary if you want to use C ++ polymorphic runtime functions. How can I get around it?
thanks
Why do I need it:
My use case can be abstracted in the following example: I have a class Integral that computes the integral of some function. Do this, they have an element that is a pointer to a class MathFunction . This abstract class contains a pure virtual function, evaluate , which takes one argument. I would like to implement a power function that I would create a class PowFunction : class MathFunction . This class will have an exponent member, and the function evaluation will look like this:
double evaluate(x){ return pow(x,exponent); }
As stated, a member of the MathFunction of class Integral must be polymorphic, which requires it to be a pointer. To answer the questions of commentators with another question. Why don't I want to make copies of MathFunction objects?
I really want Integral to “own” its MathFunction, which means that it can change parameters (for example, exponent ) without changing the MathFunction of any other integral object. This means that each Integral must have its own copy. This requires the clone () function for MathFunctions, right?
One option that I thought of: if multiple Integral objects can share the same MathFunction with a pointer to the same address, I could create copies of Integral objects without having to copy the MathFunction. But in this case, I would have to make all the const properties or somehow readonly, which is also not very elegant. Also, which Integral object should handle the removal of the MathFunction object?
Why do you need this:
Are you seriously saying that as soon as you work with polymorphic objects, you do not need a copy operation? What makes a polymorphic object different from other objects in this regard?
Using this argument, you can also throw away the copy constructor and copy assignment operator from the C ++ standard!