Monday, May 19, 2008

C++ Copy Constructor

Monday, May 19, 2008

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 ...

6 comments:

  1. Is this code doing DEEP COPY ?

    I tried to use delete obj1; in main
    but getting compilation error.

    Is obj1 & obj2 point to same location ?

    If yes then how to avoid using copy constructor ?

    ReplyDelete
  2. for keshav: obj2 is not a pointer.

    ReplyDelete
  3. Hello,
    Is it possible to make a deep copy with obj2 being a pointer type? I tried that but the default copy constructor was being called instead of the overloaded copy constructor. May be I am doing it the wrong way. Care you shed some light please mate.

    ReplyDelete
  4. Hello,
    Is it possible to make a deep copy with obj2 being a pointer type? I tried that but the default copy constructor was being called instead of the overloaded copy constructor. May be I am doing it the wrong way. Care you shed some light please mate.

    ReplyDelete
  5. str = new char(50); should be str = new char[50];
    delete str; should be delete [] str;

    ReplyDelete

 

© 2013, 2014 Programming Tutorials by SourceTricks. All rights resevered. Designed by Templateism

Back To Top