Reputation: 11
I've encountered a weird behavior during learning about implicit copy constructors in C++. This is about this bunch of code:
#include <iostream>
class Person
{
public:
char* name;
int age;
Person( const char* the_name, int the_age )
{
name = new char[strlen( the_name ) + 1];
strcpy( name, the_name );
age = the_age;
}
~Person()
{
delete[] name;
}
};
int main(){
Person p1( "Tom", 22 );
Person p2( p1 );
p2.name = "Bill";
// the output is: "Tom"
std::cout << p1.name << std::endl;
std::cin.get();
}
By default, copying an object means copying its members, therefore while creating p2
object using default copy constructor it should copy merely a pointer name
, not the character array it points to. Therefore changing name
member of object p2
should change the name
member of object p1
. Thereupon p1.name
should be "Bill"
not "Tom"
.
What's wrong in my reasoning? Why it's printing "Tom"
?
Upvotes: 0
Views: 442
Reputation: 48938
By default, copying an object means copying its members
Yes.
therefore while creating
p2
object using default copy constructor it should copy merely a pointername
, not the character array it points to.
Correct.
Therefore changing name member of object
p2
should change the name member of objectp1
.
Nope. Yes, p2.name
and p1.name
point to the same memory location, but that doesn't mean that changing the pointer value of p1.name
will change the value of p2.name
. If that were int
s, would you be surprised if changing p1.name
has no effect p2.name
? Because it's the same thing here. You have two different variables, and changing one's value doesn't change the value of the other.
int a = 0;
int b = 1;
int* ptrA = &a;
int *ptrA2 = &a;
*ptrA = 1; // now a == 1
*ptrA2 = 4; // now a == 4
ptrA2 = &b;
*ptrA2 = 10; // now b == 10
*ptrA = 3; // now a == 3, a != 10
Upvotes: 2