How to "clone" an object into a subclass object?

Vizu picture Vizu · Jul 7, 2009 · Viewed 11.4k times · Source

I have a class A and a class B that inherits class A and extends it with some more fields.

Having an object a of type A, how can I create an object b of type B that contains all data that object a contained?

I have tried a.MemberwiseClone() but that only gives me another type A object. And I cannot cast A into B since the inheritance relationship only allows the opposite cast.

What is the right way to do this?

Answer

Bryan picture Bryan · Jul 7, 2009

I would add a copy constructor to A, and then add a new constructor to B that takes an instance of A and passes it to the base's copy constructor.