Have a look at the following code you are not required to read the whole code just read the code of copy constructor and the main program.
the following statement in the copy constructor
//the statement below should do the shallow copy
ptr[currentsize++]=object.ptr[i];
this statement should do a shallow copy in case of array of pointers so please see the code of copy constructor and the main function i have mentioned the problemes in the code.
#include<iostream.h>
template<typename t>
class vector
{
public:
vector(int size);
vector(const vector<t>&);
void insert(t);
void display()const;
void makeEmpty();//sets all pointers to NULL
private:
t* ptr;
int size;
int currentsize;
};
template<typename t>
vector<t>::vector<t>(int s)
{
currentsize=0;
size=s;
ptr=new t[size];
}
//copy constructor
template<typename t>
vector<t>::vector<t>(const vector<t>& object)
{
size=object.size;
ptr=new t[size];
currentsize=0;
for(int i=0;i<object.currentsize;i++)
{
//the statement below should do the shallow copy
ptr[currentsize++]=object.ptr[i];
}
}
template<class t>
void vector<t>::insert(t element)
{
if(currentsize < size)
ptr[currentsize++]=element;
}
template<class t>
void vector<t>::display()const
{
for(int i=0;i<currentsize; i++)
{
cout<<ptr[i]<<endl;
}
}
template<class t>
void vector<t>::makeEmpty()
{
for(int i=0;i<currentsize;i++)
ptr[i]=NULL;
}
main()
{
vector<char*>object(10);
char *array[]={"zia","arshad","muneeb"};
object.insert(array[0]);
object.insert(array[1]);
object.insert(array[2]);
vector<char*> object1=object;
cout<<"displaying the new object"<<endl;
object1.display();
object.makeEmpty();//sets all pointers to NULL
//now here the object 1 should be changed but its not
cout<<"again displaying object1"<<endl;
object1.display();//still displaying the three names
cout<<endl;
system("pause");
}
You get exactly what you wrote. Your copying makes a copy of the array. You shouldn’t expect changes to the first vector touch the second one.
Note that you’ve removed pointers to the strings in the first vector. In the second they stay intact.