Sunday, March 2, 2014

Do I need a copy constructor?

Standard C++ makes heavy use of copy constructors because they are needed to support proper memory management. Referring to ref objects through handles, coupled with garbage collection, means that you don’t need copy constructors nearly as often in C++/CLIIn standard C++ the compiler will give you a default copy constructor if you do not pro-vide one. This is not the case in C++/CLI, so if you want to provide copy construction for your classes, you will need to write a copy constructor.

// UsingTrackingRefrence.cpp : main project file.

#include "stdafx.h"

using namespace System;

ref class MyClass
{
int value;
String ^str;
public:
MyClass(int v, String ^s) :value(v), str(s){}

MyClass(const MyClass %other)
{
Console::WriteLine("Copy constructor Called");
value = other.value;
str = other.str;
}
int getValue(){ return value; }
void setvalue(int v){ value = v; }
String ^getString(){ return str; }
};

int main(array<System::String ^> ^args)
{
    Console::WriteLine("\nCopy Construction");
MyClass ^one = gcnew MyClass(1, "Class One");

MyClass ^onecopy1 = one;
       Console::WriteLine("\nValue of Copy one Class:Value:{0},Str:{1}", onecopy1->getValue(),                        onecopy1->getString());
MyClass onecopy2 = *one;
onecopy2.setvalue(4);
Console::WriteLine("\nValue of one:{0}", one->getValue());
Console::WriteLine("\nValue of oneCopy2:{0}", onecopy2.getValue());
Console::WriteLine("\nStr of one:{0}", one->getString());
Console::WriteLine("\nStr of oneCopy2:{0}", onecopy2.getString());
Console::ReadKey();
    return 0;
}

OutPut:

Copy Construction

Value of copy one Class:Value:1,Str:Class one
Copy constructor called

Value of one:1
Value of oneCopy2:4

Str of one:Class one
Str of oneCopy2:Class one


No comments:

Post a Comment