Following is a template class of Vector which stores different types of data elements. check the code of copy constructor and in the main. What I was expecting that the statement “cout << vCHAR2[2] << endl;” should print the value “expense” because copy contractor is doing a shallow copy but it’s
printing “liability”.
Can anybody help me? Thanks.
template<typename T>
class Vector{
private:
T* ptr;
int size;
public:
Vector<T>(int s = 10){
size = s;
if(size!=0)
{
ptr = new T[size];
}else{
ptr = 0;
}
}
Vector<T>(const Vector<T> ©){
this->size=copy.getSize();
if(size !=0)
{
ptr=new T[size];
for(int i=0;i<size;i++)
ptr[i] = copy.ptr[i];
}else{
this->ptr=0;
}
}
~Vector<T>(){
if(size>0)
{
delete[] ptr;
}
}
int getSize() const
{
return size;
}
const Vector<T> & operator = (const Vector<T> &rhs){
if(this!=&rhs)
delete [] this->ptr;
size = rhs.size;
if(size!=0)
{
ptr=new T[size];
for(int i=0;i<size;i++)
ptr[i] = rhs.ptr[i];
}
return *this;
}
T& operator[](int index){
if(index>=0 && index<=size)
return ptr[index];
}
};
int main(int argc, char *argv[])
{
Vector<char*> vCHAR(10);
vCHAR[0]="asset";
vCHAR[1]="income";
vCHAR[2]="liability";
Vector<char*> vCHAR2(vCHAR);
vCHAR[2] = "expense";
cout << vCHAR[2] << endl;
cout << vCHAR2[2] << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
The copy ctor does a deep copy, so vCHAR2 has its own array of elements. So it doesn’t need see when you alter the elements of the source Vector. (it would see it when you altered the data you pointed to via strcpy() or access to
vCHAR[2][0]='X';(provided this wouldn’t crash your programm – as you operate on string literals))