Update 1:
Corrected nonsense code! Thanks for comments, I made a hash of the first snippet, oops.
Update 2:
Also updated question title, as the use of dynamic_cast has been pointed out as not necessary by answers.
What I’m trying to achieve here is a deep copy using strong types; I want to be able to copy Class2 to another instance of Class2; however, I also want to use the CopyTo function from the Class1 which is the base. This idea comes from my C# experience, where usually I’d just make the return type generic (see C# snippet).
void Class1::CopyTo(Class1 *c1) { // Write data in to c1 from this instance. c1->exampleData = exampleData; } // Class2 inherits Class1 Class2 *Class2::Copy() { Class2 *c2a = new Class2(); CopyTo(c2a); Class2 *c2b = dynamic_cast<Class2*>(c2a); return c2a; }
And here’s the way I’d so it in C#:
public class Class1 { T Copy<T>() where T : Class1 { /* Can't remember the best way to do this in C#; * basically if T was Class2 this would need to create * a new instance of that class, and the same goes for * Class1. */ T copy = createNewInstance(); // Copy the data from this to 'copy'. copy.exampleData = exampleData; return copy; } }
Now, compared to the C# snippet, the C++ snippet feel smelly. Is it possible to do this without pointers, or is this way best practice?
I’m not sure what you are trying to achieve because the code still doesn’t make much sense. However, I believe the following should approximate what you’re trying to do. Note that I don’t use heap memory: it’s not necessary and it would leak memory.
This works because you pass a (polymorphic) pointer to
instanceto theCopyTomethod ofClass1.Then you could call the code like this:
However, this code still smells because it’s no idiomatic C++: In C++, you would usually write a copy constructor instead. Late-bound
Copymethods do exist but they are very rarely needed, and the above is not late bound (but neither is your C# code).