How to create an object copy from a pure abstract base class reference?
c++
Solution
The typical approach commonly known as the virtual constructor idiom is to define another virtual method for cloning the concrete class, make it virtual in the abstract base, and call it as needed to produce instances of the desired class without knowing its type:
class A {
public:
A(int val): m_i(val) { }
virtual void add(int i) = 0;
virtual A* clone() const = 0; // Override in derived classes to return new B/C
int m_i;
};
Problem
I want to write a function that works for any derived classes in a certain hierarchy, without modifying the abstract class input parameter: ``` class A { public: A(int val): m_i(val) { } virtual void add(int i) = 0; int m_i; }; class B: public A { public: B(int val): A(val) { } B(): A(0) { } virtual void add(int i) { m_i += i; } }; class C: public A { public: C(int val): A(val) { } C(): A(0) { } virtual void add(int i) { m_i += i*2; } }; int f(const A& base_class) { // how to create a concrete copy of class base_class? base_class.add(5); } ``` Here f() should work for both B and C, but I can't create a copy of the concrete class because I don't know the actual type, unless I use dynamic_cast. Is there another approach to solve this problem or should just use dynamic_cast?