Why changing variable of one object reflect in another object in below code while both are separate memory

class base_class;
  virtual function do_copy(base_class rhs);
  endfunction
  virtual function copy(base_class rhs);
	do_copy(rhs);
  endfunction
  virtual function base_class clone();
	base_class base;
    base = new();
    base = this;
	base.copy(this);
    return (base);
  endfunction
endclass
class derived_class extends base_class;
  int A = 5;
  function do_copy(base_class rhs);
	derived_class derived;
	$cast(derived,rhs);
	super.do_copy(rhs);
	A = derived.A;
  endfunction
endclass

module test();
  derived_class d1,d2;
  initial
  begin
	d1 = new();
	d1.A = 10;
    $cast(d2,d1.clone());
	$display("A from d1 %0d",d1.A);
	$display("A from d2 %0d",d2.A);
    d1.A = 20;
	$display("A from d1 %0d",d1.A);
	$display("A from d2 %0d",d2.A);
  end
endmodule

Output :
A from d1 10
A from d2 10
A from d1 20
A from d2 20

===========================================================
Here d1,d2 and d3 are separate object.
d2 is clone of d1, which is a separate object.
While I change d1.A to 20, why d2.A is also changed?

It rather looks like that because you initialized A in the same statement as you declared it, the compiler has taken A to be a static variable. Sure behaves like one. I would try removing the initialization (= 5) from the declaration of A. If you want all object of this class to start with a value of 5 for A, add an initial block and initialize A to that value there.

In reply to Jinam Shah:

Problem is in line “base = this;” in your base_class::clone() method. This line masks the “base=new;” above it and just make the base handle points to the “d1” object. So at the end the clone does not return a new object, but rather a handle that points to the same object, i.e. both “d1” and “d2” point to the same memory location.
To fix this your have to fix your base_class::clone() method and add some infra structure.


//--ADDED--
`define my_create(TYPE) \
  virtual function base_class create (); \
    TYPE t = new; \
    return t; \
  endfunction  
  
class base_class;
  //--ADDED--
  `my_create(base_class)
  virtual function do_copy(base_class rhs);
  endfunction
  function copy(base_class rhs);
	do_copy(rhs);
  endfunction
  virtual function base_class clone();
    base_class base;
    //base = new();   //--COMMENTED--
    //base = this;    //--COMMENTED--
    base = this.create();   //--ADDED--
    base.copy(this);
    return (base);
  endfunction
endclass
class derived_class extends base_class;
  //--ADDED--
  `my_create(derived_class)
  int A = 5;
  function do_copy(base_class rhs);
    derived_class derived;
    $cast(derived,rhs);
    super.do_copy(rhs);
    A = derived.A;
  endfunction
endclass