I was trying to recap basics in C++ and was looking into the copy constructor and came across a scenario of deep copy for char*
What happened was even after allocating the memory separately for both pointers, Was able to see the object being pointed to the same address.
Can anyone point out the reason?
#include <iostream>
class Test{
public:
char *c;
Test(char a){
c = new char();
*c = a;
}
Test (const Test& obj){
c = new char();
this->c = obj.c; //This line is not working as expected
}
char getValue(){
return *c;
}
void setValue(char a){
*c = a;
}
char* getAddress(){
std::cout << "Address is " << c << std::endl;
}
};
int main()
{
Test t1 ('a');
Test t2 = t1;
std::cout << "t1.c " << t1.getValue() << std::endl;
std::cout << "t2.c " << t2.getValue() << std::endl;
t1.getAddress();
t2.getAddress();
t2.setValue('z');
std::cout << "t1.c " << t1.getValue() << std::endl;
std::cout << "t2.c " << t2.getValue() << std::endl;
t1.getAddress();
t2.getAddress();
return 0;
}
But if i use strcpy for copying its working as expected!
Test (const Test& obj){
c = new char();
strcpy(this->c, obj.c);
}
Thanks