Class object queue doesn't provide proper value

Hi,

The packets stored in class object queue is not correct. I have added 2 objects in the queue, but when I read back the queue, both packets are second, not the First and Second. Anybody has come across this kind of issue?

---------- I have tried following code: -----------

class packet;
  rand bit [15:0] sip;
  rand bit [15:0] dip;
  rand bit [15:0] sport;
endclass

module tb;
  initial begin
    packet p;
    packet p2;
    packet p3;
    packet p_q[$];
    int p_size = 2;
    int i=0;
    
    p2 = new();
    p3 = new();

    for(i=0; i<p_size; i++) begin
      p2.sip   = ('h701 + i);
      p2.dip   = ('h801 + i);
      p2.sport = ('h901 + i);
      p_q.push_back(p2);
    
      $display("p2.sip   = 'h%0h",p2.sip);
      $display("p2.dip   = 'h%0h",p2.dip);
      $display("p2.sport = 'h%0h",p2.sport);
    end

    for(int i=0; i<p_size; i++) begin
      $display("p_q[%0d].sip   = 'h%0h",i,p_q[i].sip);
      $display("p_q[%0d].dip   = 'h%0h",i,p_q[i].dip);
      $display("p_q[%0d].sport = 'h%0h",i,p_q[i].sport);
    end
  end
endmodule

In reply to navdeepp5:

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

Your problem is you are only constructing one packet class object and storing its class handle into the class variable p2. Then you go through the for loop modifying the same object and pushing the same class handle into the queue. Then all elements of p_q reference the same object.

You need to move the construction of the packet class object inside the first for loop so that each iteration pushes a different packet object handle onto the p_q queue.

In reply to dave_59:

Thanks Dave. I understood now why it was not writing proper values.