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
	{
	public:
		property int SomeInt;
		property String ^SomeString;
		array<SomeOtherClass^> ^SomeOtherClassArray;

		//----- CONSTRUCTOR -----
		MyClass::MyClass(void)
		{
			//Strings and arrays will be nullptr until created
		}

		//----- DEEP COPY CONSTRUCTOR -----
		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
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

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