Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

What is the difference between the two code executions below?

Status
Not open for further replies.

jdshah

Junior Member level 3
Joined
Dec 17, 2010
Messages
28
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Ahmedabad
Activity points
1,481
What is difference between below two code execution

Code 1:
Code:
class_p p1,p2;
p1 = new();
p2 = new();
p2 = p1;

Code 2:

Code:
class_p p1,p2;
p1 = new();
p2 = new p1;

What is difference between above two. I understand both are same. (like, p2 = new p1; would in turn do p2 = new; p2 = p1;)
But it is not. In code 1, variable changed in p1 will be reflected in p2. But in code 2 variable changed in p1 would not change value in p2.
 

Re: What is difference between below two code execution

Remember that p1 and p2 are class variables that reference a class object using a handle to the object.

Code 1 constructs two objects and places their handles in p1 and p2 respectively. Then you assign the handle stored in p1 to p2 and both now refer to the first object constructed. You lose the handle to the second object. Let's assume class_p is defined as
Code:
class class_p;
 int m;
 function new;
   m = 5;
 endfunction
endclass
now p1.m and p2.m refer to the same variable m because they both are referring to the same object. If you made the assignment p1.m = 6, p2.m would be 6 as well.

Code 2 constructs one object, placing a handle to that object in p1. Then it constructs another object and places a handle to that object in p2. However, instead of calling the constructor new(), it copies all the class member values that p1 refers to and assigns them to the members of the object that p2 refers to. This is known as a shallow copy. So if you had

Code:
class_p p1,p2;
initial begin
  p1 = new();
  p2 = new();
  p2.m = 6;
  p2 = p1;
  $display(p1.m,, p2.m)  // 5 5
  p1.m = 7;
  $display(p1.m,, p2.m)  // 7 7
  p1 = new();
  p1.m = 6;
  p2 = new p1;
  $display(p1.m,, p2.m)  // 6 6
  p1.m = 7;
  $display(p1.m,, p2.m)  // 7 6
end
 
Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top