Virtual methods in system verilog

In reply to Deepthip:

In your 2nd code, you have the task(my_run) which has the argument of type base class. So, when you call “my_run(m_pkt)”, in fact, you are passing an object of type derived class to a handle of type base class (like Base_handle = Derived_Object). Hence it will still call base class method since it is non-virtual.

In your 1st code, you are directly calling “derived_object.method()”, hence, the derived class method is getting called.

Please use the code tags.

typedef enum {IDLE, RUN, P0, P1} cmd_t;

class Packet;
  cmd_t cmd;
  int status;
  bit [7:0] data [0:255];

  function void SetStatus (input int y);
    status = y;
    $display("base");
  endfunction: SetStatus
  
endclass: Packet


class myPacket extends Packet;
  bit errBit;

  function bit ShowError();
    return(errBit);
  endfunction: ShowError

  function void SetStatus (input int y);
    status = y + 2;
    $display("child");
  endfunction: SetStatus

endclass: myPacket


module top;
  Packet pkt = new;
  myPacket m_pkt = new;

  task my_run (Packet PKT);
    PKT.SetStatus(2);
    $display("Status value is = %0d", PKT.status); 
  endtask: my_run

  initial begin
    pkt.SetStatus(2);
    $display("Status value is = %0d", pkt.status);
    m_pkt.SetStatus(2);
    $display("Status value is = %0d", m_pkt.status);
    my_run(pkt);
    my_run(m_pkt);
  end
endmodule: top