I have a base class A and classes B and C are derived from it. A is an abstract class, and all three classes have a constructor that takes 2 arguments. Is it possible to make a method in the base class A like this:
A* clone() const
{
return new this.GetType(value1, value2);
}
and if the current object whose clone()-function is being called is for example C, the function will return the pointer to a new object of class type C?
This looks like C++.NET (a.k.a. “managed C++”) rather than plain (standard) C++. I’m not an expert on this, but my guess (assuming .NET) would be that you’d have to use reflection to instantiate an object of a
System.Type. The usual steps are:Typeobject, e.g. by callingGetType.ConstructorInfo(Type.GetConstructors()IIRC)ConstructorInfo.Invoke()to create an instanceSystem.Objectto the desired type.In regular C++, you can’t do this at all, because the language simply doesn’t have reflection, and type information is mostly lost at run time (RTTI can compare and test run-time types of objects, but that’s about it). You’ll have to implement a new clone method for each derived class; the pattern I usually use looks something like this: