Shallow and Deep Copying

car(int p,int mn,char* n)
{
price=p;
modelno=mn;
int l=strlen(n);
name=new char[l+1];
strcpy(name,n);
}
int main()
{
car C(100,200,“Audi”);

Here n is the pointer pointing to the string audi.
In this parameterised copy constructor first we are allocating a memory of size (strlen(n)+1) size in heap and pointer (name) is pointing to it.
Then we are doing strcpy(name,n) making name point where n is pointing i.e string audi .
So why are we allocating (strlen(n)+1) size memory in heap ?

@POORVI_SAXENA,
Try replacing those three lines with name = n.

Its working fine so why are we allocating memory?

@POORVI_SAXENA,
It isn’t necessary, but doing it isn’t wrong as well right…?

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.