Deep copy

Hi,
I am having a argument with someone on the use of deep copy. I was convinced by the other guy until i run my deep copy function and find it works.

Basically if I want to do a deep copy, say

class A
  int c;
endclass

class B
  A a
  int i;
  function new();
    a = new();
  endfunction
endclass

i said to have a copy function inside Class B like this

function copy(A a);
    this.a = new a;
endfunction

B b1,b2;
initial
 begin 
  b1 = new();
  b1.a.c = 1;
  b1.i = 0;
  b2 = new b1;
  b2.copy(b1.a);
 end

so he said this wouldn’t work because "this.a = new a " is copying the handle value passed from b1.a so this.a will still have the same memory location. And I sort of agreed because copy using new is shallow copy, but when I run my code, i found out the when i change “b1.a.c = 2;”, my b2.a.c would stay at 1 so it means it has a new memory location already. The other guy suggest me to write another copy function inside Class A to really do deep copy but i found without having that class also works as a deep copy.

Can someone kindly explain?

Besides, I do have another question regards writing a function to clone struct.

struct Node{
int a;
bit map[string];
Node nextNode;
}

How to clone the associative array is my main concern since i think it doesn’t take any memory location until it is used.
Any help is much appreciated!

In reply to goodice:

The end result of your code behaves the same as a deep copy, but the method is not the same as a deep copy. Your code “works” because class A has no class members, and class B has only one class member. It does not scale. Suppose class A gets modified.

class A;
 int c;
 AA aa=new;
end

Now your copy method in B no longer works. You want to keep the copy method together with the class.

class A;
  int c;
  function void copy(A rhs);
    this.c = rhs.c;
  endfunction
  class B;
    A a;
    int i;
    function void copy(B rhs);
      this.a = new;
      this.a.copy(rhs.a);
      this.i = rhs.i;
    endfunction
endclass

B b1, b2;
initial begin
  b1 = new();
  b1.a.c = 1;
  b1.i = 0;
  b2 = new();
  b2.copy(b1);
 end