Sunday, June 27, 2010

Deep Copy

  1. needed when the class has dynamically allocated members
  2. always remember the explicit this pointer of c++
  3. copy constructor is implemented (algorithm)
    1. allocate memory for dynamically allocated members
    2. copy the data from const_argument.member to this.member
  4. assignment operator is implemented (algorithm)
    1. check for self assignment
    2. delete memory for this.member
    3. allocate new memory for this.member
    4. copy the data from const_argument.member to this.member
    5. return this
  5. when copy constructor is called
    1. doing initialization with objects, like
      1. class1 object1(“value”);
      2. class1 object2 = object1; //object to object assignment
    2. passing a object by value
    3. returning a object by value
  6. when assignment operator is called
    1. assigning a existing object(object with memory for its data members) a new object
CODE SNIPPET
1: #include <iostream>
2: #include <malloc.h>
3: #include <stdio.h>
4: #include <string.h>
5: using namespace std;
6: 
7: class A
8: {
9: public:
10:   //ctor
11:   A()
12:   {
13:     cout<<"inside  ctor"<<endl;
14:     name = (char*)malloc(10);
15:     name = "test";
16:   }
17:   
18:   //~dtor
19:   ~A()
20:   {
21:     free(name);
22:     name = NULL;
23:   };
24:   
25:   //copy ctor
26:   A(const A&);
27:   
28:   //assignment operator
29:   A& operator = (const A&);
30:   
31:   void showName(){std::cout<<name<<endl;};
32:   
33: private:
34:   char *name;
35: };
36: 
37: main()
38: {
39:   A obj1;
40:   obj1.showName();
41:   A obj2(obj1);//copy ctor is called
42:   obj2.showName();
43:   A obj3 = obj1;//copy ctor is called
44:   A obj4;
45:   obj4 = obj1;//assignment is called
46:   getchar();
47: }
48: 
49: //allocate memory for the data members
50: //copy data members
51: A::A(const A& copyof)
52: {
53:   cout<<"inside copy ctor"<<endl;
54:   name = (char*) malloc(10);
55:   strcpy(name,copyof.name);
56: }
57: 
58: //check for self assignment
59: //free the existing memory for .this object members
60: //allocate new memory for .this object members
61: //copy the data to .this
62: //retrun this, for operator chaining, cascade assignments
63: A& A::operator =(const A& obj)
64: {
65:   cout<<"assignment called"<<endl;
66:   if(this != &obj)
67:   {
68:     free(name); 
69:     name = (char*)malloc(10);
70:     strcpy(name,obj.name);
71:   }
72:   return *this;
73: }

No comments: