Deep copy vs Shallow copy:
- Deep Copy copies all the dynamically allocated members properly to destination.
- Deep copy is safe and prevents memory corruptions or memory overwriting.
- When dealing with string, list, vectors, or any other dynamically allocated members deep copy is mandatory.
Example:
Comment out the below functions in the following example and see how you face problem at runtime.
#include<string.h>
#include<iostream.h>
class User
{
protected:
int user_id;
char *user_name;
public:
User()
{
user_id = 0;
user_name = new char[10];
}
~ User()
{
user_id = 0;
delete [] user_name;
}
int get_id()
{
return user_id;
}
void set_id(int id)
{
user_id = id;
}
char* get_name(void)
{
return user_name;
}
void set_name(char* name)
{
strcpy(user_name, name);
}
/*Comment out this function*/
User(User &u)
{
user_id = u. user_id;
user_name = new char[10];
strcpy(user_name, u.user_name);
}
/*Comment out this function*/
User & operator = (User &u)
{
user_id = u. user_id;
strcpy(user_name, u.user_name);
return *this;
}
};
void main(int argc, char *argv[])
{
User user1;
user1.set_id(1);
user1.set_name("User1");
User user2(user1);
cout << "User1 id " << user1 .get_id()
<< ", User1 name " << user1 .get_name() << endl;
cout << "User2 id " << user2 .get_id()
<< ", User2 name " <<user2 .get_name() << endl;
cout.flush();
user1.set_id(2);
user2.set_name("User2");
cout << "User1 id " << user1.get_id()
<< ", User1 name " << user1 .get_name() << endl;
cout << "User2 id " <<user2.get_id()
<< ", User2 name "<<user2 .get_name() << endl;
cout.flush();
}
About our authors: Team EQA
You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.