Yahoo Interview Question
Software Engineer / Developerscopy constructor can do a deep copy whereas assignment is merely a shallow copy ie references.
A copy constructor initialises a new object from an already existing object. An assignment operator is used to copy values from one object to an already existing object.
The key difference here is that for assignment operator the target object already exists.
I think the difference lies in the fact that using a copy constructor allows you to make a deep copy while the assignment operator only makes a shallow copy.
A sample code for copy constructor.. though i have not made use of it for making a deep copy.. will post it soon
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct copy_variable
{
public:
int abc_1;
int abc_4;
char abc_2;
char abc_3[10];
copy_variable()
{
}
copy_variable(const copy_variable& some_object):abc_2('a'),abc_1(1000)
{
abc_1 = some_object.abc_1;
strcpy(abc_3,"something");
abc_4 = 0;
cout<<"The values of abc_1, abc_2, abc_3\n" <<abc_1<<abc_2<<abc_3;
}
int char_string ();
};
int main()
{
copy_variable object_1;
copy_variable object_2(object_1) ;
object_1.abc_1 = 100;
object_1.abc_2 = 'm';
strcpy(object_1.abc_3, "the");
object_1.abc_4 = 100;
copy_variable object_3 = object_1;
//cout << "values of object 3 \n"<< object_3.abc_1<<object_3.abc_2;
return 0;
}
Sorry for the wrong code above--
Here s a the proper one
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct copy_variable
{
public:
int abc_1;
int abc_4;
char abc_2;
char abc_3[10];
copy_variable()
{
}
copy_variable(const copy_variable& some_object):abc_2('a'),abc_1(1000)
{
abc_1 = some_object.abc_1;
strcpy(abc_3,"something");
abc_4 = 0;
cout<<"The values of abc_1, abc_2, abc_3" <<"\t"<<abc_1<<"\t"<<abc_2<<"\t"<<abc_3<<"\n";
}
int char_string ();
};
int main()
{
copy_variable object_1;
object_1.abc_1 = 100;
object_1.abc_2 = 'm';
strcpy(object_1.abc_3, "the");
object_1.abc_4 = 100;
copy_variable object_2(object_1);
return 0;
}
www . cs . nyu . edu / ~ xiaojian / bookmark / local / copyCplus . pdf
- Coder December 03, 2009