Difference between ref argument for copy method (refer below code)

hi…
In SystemVerilog when used ref as an argument for copy method like shown in below code.
also, I want to know the difference between the below copy methods, the used case of them and their advantages…

class test;
 //put some property or variable

 function void copy1 (ref test obj);
  if(onj == null) obj = new;
  obj.xyz = this.xyz;
  obj.abc = this.abc;
  ....
 endfunction

 function void copy2 (test obj);
  if(onj == null) obj = new;
  obj.xyz = this.xyz;
  obj.abc = this.abc;
  ....
 endfunction

 function test copy3 (test obj);
  if(onj == null) obj = new;
  obj.xyz = this.xyz;
  obj.abc = this.abc;
  ....
 endfunction

 function test copy4 (ref test obj);
  if(onj == null) obj = new;
  obj.xyz = this.xyz;
  obj.abc = this.abc;
  ....
 endfunction
endclass:test1

In reply to Kashyap_14:

Please use code tags making your code easier to read. I have added them for you.

The code for copy2/3 and copy1/4 are identical. Did you mean to have some differences?

In practice, people write copy() methods that do not call the constructor. Construction followed by copying is usually done with a virtual clone() method. You might want to take a look at my short course on classes, especially the second section.

The default task/function argument direction is input which is what you use in copy2/3. That means the actual argument used when you call the function gets copied into the function’s formal argument, but it does not get copied out. So when you make an assignment to obj when calling the new() constructor, that handle is lost when you exit the function. You should use inout which copies the actual argument upon entering the function, and copies the formal argument back to the actual argument when returning from the function.

A ref argument never gets copied. It gives you an indirect reference to the actual argument from inside the function/task. Realize that the contents of a class variable is a handle that references a class object. So when I talk about copying or not copying the argument, I’m referring to the handle, not the contents of the object.

ref arguments are much more useful in time consuming tasks when you need to observe changes in the argument while the task is active, not just when entering or exiting the task. ref arguments have more strict type compatibility requirements that make them less desirable for use in functions.

In reply to dave_59:

Thanks a lot to aware this concept