Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
explain the copy constructor, shallow copy, and deep copy with examples and c++ code
#1
respected sir plz explain the copy constructor, shallow copy, and deep copy with examples and c++ code. thanks
Reply
#2
A copy constructor is used to initialize a newly declared Object from an existing Object. This makes a deep copy like assignment.
A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory.

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences.


I am giving you one example which perform deep copy in this example if you do not override copy constructor then it will give run time error, not perform as what we want so it will be help full for understanding why we have tooverride copy constructor if compiler provide it by default.

class base
{
int *a;
public:
base()
{}
void allocate()
{
a = new int(10);
}
void disp()
{
cout<<*a<<endl;
}
base(base &b)
{
a = new int(*(b.a));
}
~base()
{
delete a;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
base *b1 = new base;
b1->allocate();
base *b2 = new base(*b1);
b1->disp();
delete b1;
b2->disp();
delete b2;
return 0;
}

0300-9520262
Get solution in 24 hour
|cpmputer & internetConfusedmileys81:[SIZE="4"][SIZE="3"]....[/SIZE][/SIZE]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dangling Pointers Explain in C++ Vuhelper 0 7,270 05-31-2012, 01:52 AM
Last Post: Vuhelper
  Explain the difference b/w Null Pointer and Null Nodes? C++ 2012 Vuhelper 0 1,951 01-06-2012, 12:24 AM
Last Post: Vuhelper
  ASCII code is binary numbers of 0 and 1 in C++ 2012 Vuhelper 0 2,278 01-04-2012, 10:41 PM
Last Post: Vuhelper
  explain this operator -> which is use as headnode->stnext(null); Vuhelper 0 1,724 01-04-2012, 10:26 PM
Last Post: Vuhelper
  int x[10]; x[0]= 1; x[1]=2; if following code is executable in C++ 2012 Vuhelper 0 1,935 01-04-2012, 10:17 PM
Last Post: Vuhelper
  array project code c++ 2011 Vuhelper 0 1,274 12-10-2011, 06:32 PM
Last Post: Vuhelper
  factorial in C++ code 2011 Vuhelper 0 944 12-10-2011, 06:31 PM
Last Post: Vuhelper
  Is constructor necessory in c++? And if than why? Vuhelper 0 1,922 11-05-2011, 05:12 PM
Last Post: Vuhelper
  ASCII to char conversion code in C++ 2011 Vuhelper 0 1,721 11-05-2011, 05:01 PM
Last Post: Vuhelper
  C++ with loop code 2011-12 Vuhelper 0 978 09-18-2011, 07:09 PM
Last Post: Vuhelper

Forum Jump:


Users browsing this thread: 1 Guest(s)