1

I'm trying to grasp the concept of casting in SystemVerilog and have been tinkering with the following code:

class packet;

  virtual function int compute_crc();
    compute_crc = 12345; 
  endfunction

  virtual task print;
    $display("This is a packet");
  endtask

endclass: packet

class bad_packet extends packet;

  function int compute_crc();
    compute_crc = 54321;
  endfunction

  task print;
    $display("This is a bad packet");
  endtask

  task print2;
    $display("This is not accessible from base");
  endtask

endclass: bad_packet

module test;
  packet        pkt;
  bad_packet    b_pkt;

  initial begin
    b_pkt = new();

    pkt = b_pkt;   

    $cast(b_pkt, pkt);
    b_pkt.print;
    pkt.print;

  end  
endmodule

I have a base class 'packet', and a derived class 'bad_packet'. By using $cast, will I be able to access bad_packet's method print2? Are there other ways of doing this? Thanks!

je_pat
  • 15
  • 4

1 Answers1

0

Yes, using $cast is the typical way to get access to all the methods that do not exists as virtual methods in the base class. Think about it - if you know you want to call something that only exists in an extended class, you need to know the type of that extended class, so you will always be able to declare a class variable of that type and $cast to it.

There is also an indirect way of calling a non-virtual method in the extended class, but it still involves calling a virtual method in the base class. You call a virtual method that gets you into the extended class, that that method can call anything in the extended class object. This is what the clone()/copy() methods do in many methodologies.

dave_59
  • 39,096
  • 3
  • 24
  • 63
  • 1
    I was able to access bad_packet's compute_crc method from packet class but what I'm trying to access is bad_packet's print2 method from inside packet class, an error is flagged because that method does not exist inside packet. So does that mean I can only access methods from extended class only if a virtual version of that method also exist in the base class? – je_pat Sep 21 '15 at 00:26
  • 1
    You can only access methods in an **extended class object** whose handle is stored in a **base class variable** if the method is defined as virtual method in the **base class type**. – dave_59 Sep 21 '15 at 04:59