Tuesday, February 15, 2011

What is deep copy constructor?

What is deep copy constructor?

Overriding default copy constructor with a constructor which copies all the members including all dynamically allocated members is called deep copy constructor.


Example:

#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
 
class Student
{
public:
      Student(char* szName,int nAge)
      {
           m_szName =new char[20];
           strcpy(m_szName,szName);
           m_nAge=nAge;
      }
     Student(const Student &obj )
      {
           m_szName =new char[20];
           strcpy(m_szName,obj.m_szName);
           m_nAge=obj.m_nAge;
      }
      ~Student()
      {
           delete[] m_szName;
           m_szName=NULL;
           cout<<"Memory destroyed \r\n";
      };
      int m_nAge;
      char *m_szName;
};
 
int main()
{
     Student *ptr=new Student("John",12);
     cout<<"Name: "<<ptr->m_szName<<"\r\n"<<"Age: "<< ptr->m_nAge<<"\r\n";
     {
          Student obj( *ptr);
          cout<<"Name: "<<obj.m_szName<<"\r\n"<<"Age: "<< obj.m_nAge<<"\r\n";
          //obj scope ends and ~Student() will be called
     }
     cout<<"Name: "<<ptr->m_szName<<"\r\n"<<"Age: "<< ptr->m_nAge<<"\r\n";
     delete ptr;
     getch();
     return 0;
}

Result:

Name: John
Age: 12
Name: John
Age: 12
Memory destroyed
Name: John
Age: 12
Memory destroyed

No comments:

Post a Comment