Default copy constructor of compiler copies all the member variables
from source to destination object. This is called shallow copy
constructor.
Example:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Student
{
public:
Student(int nAge)
{
m_nAge=nAge;
}
int m_nAge;
};
int main()
{
Student obj(13);
cout<<"Age1: "<< obj.m_nAge<<"\r\n";
Student obj1(obj);
cout<<"Age2: "<<obj1.m_nAge<<"\r\n";
getch();
return 0;
}
Result:
Age1: 13
Age2: 13
Example 2:
#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()
{
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
}
//Will Crash here
//because m_szName is already freed in destructor.
// this is the problem with shallow copy
cout<<"Name: "<<ptr->m_szName<<"\r\n"<<"Age: "<< ptr->m_nAge<<"\r\n";
delete ptr;
getch();
return 0;
}
Result:
Crash!!!!!!!!!!!
No comments:
Post a Comment