• Post Reply Bookmark Topic Watch Topic
  • New Topic

copy constructor and aliasing  RSS feed

 
nick Mercado
Greenhorn
Posts: 12
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have question about copy constructor and aliasing.
For example,


Result
s1_id: 1234
s1_name: Karen

s1_id: 1234
s1_name: Karen

s3_id: 5678
s3_name: Tim

s3_id: 5678
s3_name: Tim


so basically copy constructor and aliasing the same thing?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. For aliasing, you have to be pointing to the same location in memory. If you set the name field of s2 and s4 to a new value, you'll see a different impact on s1 and s3.
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are some subtleties, like the behavior of == vs equals().



 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carey Brown wrote:. . . behavior of == vs equals(). . . .
Yes, your example shows that == demonstrates there are now two different objects and equals() shows both objects have the same content. What you are doing is making a defensive copy, which you can read about here and here. The second link appears to be an excerpt from Effective Java™ by Joshua Bloch.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!