Hi
I am having difficulty understanding the error I am getting from the code below for the clone method-
The error is pointing at line 42 in the clone function of the extended class C.
class A;
int val;
function new();
val = 1;
endfunction
function void copy(A h);
h.val=this.val;
endfunction
endclass
class B;
int val;
A a;
function new();
a=new();
val = 2;
a.val=3;
endfunction
function void copy(B h);
h.val = this.val;
this.a.copy(h.a);
endfunction
virtual function B clone();
B h=new();
this.copy(h);
return h;
endfunction
endclass
class C extends B;
function new();
super.new();
endfunction
function void copy(C h);
h.val = this.val;
super.copy(h);
endfunction
virtual function B clone();
$display("Method call from C");
C h1=new();
this.copy(h1);
return h1;
endfunction
endclass
module tb;
B b1,b2,b3,b4;
C c1,c2,c3;
initial begin
b1=new();
b2=new b1; //remember this syntax for shallow copy
$display("b2.a.val %h b1.a.val-%h",b2.a.val,b1.a.val);
$display("changing values in b1.a.val");
b1.a.val=10;
$display("ShallowCopy: b2.a.val %h b1.a.val-%h",b2.a.val,b1.a.val);
$display("deep copy-");
b2=new();
b1.copy(b2);
b1.a.val=20;
$display("Deep copy: b2.a.val %h b1.a.val-%h",b2.a.val,b1.a.val);
$display("clone method- its a virtual function so polymorphism can be used");
b3=b1.clone();
b3.a.val=30;
$display("clone: b3.a.val %h b1.a.val-%h",b3.a.val,b1.a.val);
b4=c1;
c2=b4.clone();
$display("clone extend: b3.a.val %h b1.a.val-%h",b3.a.val,b1.a.val);
end
initial begin
#10 $finish;
end
endmodule
I have an additional question.
I understand if we pass a handle as an argument to a function, it is a reference to an object, so I can make changes to the object’s properties.
But if a handle is not pointing to an object yet and I call a constructor in the function, I seem to be losing the values after the end of function call.
for example-
if I write clone function as-
virtual function void clone(B h);
h=new();
this.copy(h);
endfunction
and try to use it as
B b1,b2;
b1.clone(b2);
This doesn’t work for me. Please explain it as well.
Thanks in advance!