Copying A Class

If your class has no pointer and no dynamic memory allocation then you don’t need to provide a copy function – you can use ‘=’.
However if this isn’t true (i.e. your class contains a string or other object), then you need to provide a copy function or otherwise if you try and copy the class the handle will simply be copied instead.

Shallow Copy

Use the MemberwiseClone method to make a shallow copy of a class.  This is a bitwise copy of your type. which will make a copy of the type and all contained value types and references types.  However, it will not copy the objects that the reference type members in your type refer to.  I.e. It is a copy of the first level of your type.

	MyClass1 = MyClass->MemberwiseClone();

Deep Copy

Create a 2nd constructor for the class which takes an existing class object:

	public ref class MyClass
		property int SomeInt;
		property String ^SomeString;
		array<SomeOtherClass^> ^SomeOtherClassArray;

		//----- CONSTRUCTOR -----
			//Strings and arrays will be nullptr until created

		MyClass::MyClass(MyClass ^MyClassToCopy)
			int Count;

			SomeInt = MyClassToCopy->SomeInt;
			SomeString = MyClassToCopy->SomeString;

			SomeOtherClassArray = gcnew array<SomeOtherClass^>(MyClassToCopy->SomeOtherClassArray->Length);
			for (Count = 0; Count < MyClassToCopy->SomeOtherClassArray->Length; Count++)
				SomeOtherClassArray[Count] = gcnew SomeOtherClass(MyClassToCopy->SomeOtherClassArray[Count]);		//Perform a deep copy of the other class


Then you can copy like this

	MyClass ^MyClass1 = gcnew MyClass();			//Creat an object
	MyClass ^MyClass2 = gcnew MyClass(MyClass1);	//Deep copy it to a new object
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.


Your email address will not be published. Required fields are marked *