Shallow copy

Hello…I am a kind of stuck in concept regarding shallow copy while working on the following piece of code…
Actually…as far as i know, in case of shallow copy, only pointers are copied, like let us suppose, we are having A class B having handle b1 i.e. pointing to some memory (in which variable value is stored), now we are having b2 as shallow copy of b1; so if we’ll access variable “i” through handle b2 and give it some another value, then variable “i” value will be overwritten, so if we’ll display both b1.i and b2.i, then it should give us new overwritten value…but its not happening in following case…

Example1:

class B; 
int i; 
endclass 

program main; 
initial 
begin 
B b1; 
B b2; 
b1 = new(); 
b1.i = 123; 
b2 = new b1; 
b2.i = 321; 
$display( b1.i ); 
$display( b2.i ); 
end 
endprogram

Result
123
321

Although, if we’ll try the below given example, then we’ll get the overwritten results as it should be in shallow copy.

example 2::

class A; 
int i; 
endclass 

class B; 
A a; 
endclass 

program main; 
initial 
begin 
B b1; 
B b2; 
b1 = new(); 
b1.a = new(); 
b1.a.i = 123; 
b2 = new b1; 
$display( b1.a.i ); 
$display( b2.a.i ); 
b1.a.i = 321; 
$display( b1.a.i ); 
$display( b2.a.i ); 

end 
endprogram

RESULT

123
123
321
321

Could someone please explain me that why is there difference in overwriting in both the cases of shallow copy?
Thanks in advance!!

The LRM says about “shallow copy”,

“All of the variables are copied across integers, strings, instance handles, etc. Objects, however, are not copied, only their handles; as before, two names for the same object have been created.”

Once copied, the copy becomes an independent entity. The copied variable is a new variable, which intially has the same value as the original.

An object handle, once copied, is a new handle, initially pointing to the same object as the original.

So in example 1, b2.i is a new variable, independent of b1.i. Its initial value is the same as that of b1.i, but after that, there is no connection between them.

In example 2, b2.a points to the same class object as b1.a. You could change b2.a to point to a different object, but you did not. As long as they point to the same object, b2.a.i and b1.a.i are the same.

Regards,
Shalom