GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  Programming  >  C++

 Print  |  
Question:  what is importance of const. pointer in copy constructor?



September 09, 2006 06:11:42 #5
 ramachandra   Member Since: Visitor    Total Comments: N/A 

RE: what is importance of const. pointer in copy const...
 

Copy constructor is useful when an object is initialized with another existing object or an object is passed by value to a function or an object is returned by value from a function. Shallow copy is nothing but copying members of a class by value so when an object is copied into another object all members will copied by value and if dynamic memory allocation is there the pointer will be copied but not the memory to which the pointer is pointing too. So the pointers in old and new pointing to same memory allocation. If the old objects is deleted, memory to pointer is also deleted. In this case when the new object trying to access the same memory crash will happen. This can be avoided with copy constructor explicit declaration. in the below code I created memory to the char pointer name again in copy constrctor and copied the value. I hope this gives you better idea.. Thanks

#include<iostream.h>
#include<string.h>

class A

{public:

char *name;

A(){

name = new char[20];

strcpy(name,"ramachandra");

}

A(const A &a)

{

name = new char[20];

strcpy(name,a.name);

}

};

void main()

{

A a;

cout<<a.name n;

A b = a;

cout<<b.name n;

}

     

 

Back To Question