Monday, May 19, 2008

C++ Copy Constructor

2 comments
What is a copy constructor?
  • The default copy constructor created by the compiler performs a bitcopy.
  • When the class members are dynamically allocated it becomes necessary to write our own implementation of copy constructor.
  • The copy constructor essentially performs a deep copy when a object is created using another object.

EXAMPLE: Demostrates the need of copy constructor


#include <iostream>

using namespace std;

class MyClass {
private:
char* str;
public:
MyClass();
MyClass(const MyClass& obj);
void Print();
~MyClass();
};

MyClass::MyClass()
{
cout << "In constructor ..." << endl;
str = new char(50);
strcpy(str, "Hello World");
}

MyClass::MyClass(const MyClass& obj)
{
cout << "In copy constructor ..." << endl;
str = new char(50);
strcpy(str, obj.str);
}

void MyClass::Print()
{
cout << str << endl;
}

MyClass::~MyClass()
{
cout << "In destructor ..." << endl;
delete str;
}

void main()
{
MyClass* obj1 = new MyClass();
obj1->Print();

MyClass obj2(*obj1);
delete obj1;

obj2.Print();
}

OUTPUT:
In constructor ...
Hello World
In copy constructor ...
In destructor ...
Hello World
In destructor ...
If You Enjoyed This, Take 5 Seconds To Share It

2 comments: