首页 > 解决方案 > How can one access a base class method using base class object once it has been overwritten?

问题描述

This question might be applicable to all/most Object-oriented programming languages but I am only concerned about the SystemVerilog side. Polymorphism, I thought I understood, until I was talking to a colleague the other day and this came and I realised that I don't know how this can be done. Following are the two classes to consider for the purpose of this discussion -

class four_wheeler;

    virtual function void vehicle_type();
        $display("Four-wheeler");
    endfunction:vehicle_type

    virtual task colour();
        $display("Many colours");
    endtask:colour
endclass:four_wheeler

class jaguar extends four_wheeler;

    function void vehicle_type();
        $display("Jaguar");
    endfunction:vehicle_type

    task colour();
        $display("Black");
    endtask:colour
endclass:jaguar

program sv_prog;

  initial begin
    four_wheeler four_wheeler_h;
    jaguar  jaguar_h;

    four_wheeler_h = new();
    jaguar_h = new();

    four_wheeler_h = jaguar_h;
    four_wheeler_h.vehicle_type();

  end

endprogram: sv_prog

I want to access the vehicle_type() function in the base class four_wheeler using its own object. I can do this by four_wheeler_h.vehicle_type() before the four_wheeler_h = jaguar_h copy. Regular OOP working! But can I do it after the copy of the handle? I can use the super keyword in jaguar class vehicle_type() method:

function void vehicle_type();
    super.vehicle_type();
    $display("Jaguar");
endfunction:vehicle_type

and get the output:

Four-wheeler
Jaguar

But I am more interested in doing this from the program block itself without having to modify the function in the jaguar class. Is there any way I can achieve that? Maybe a use of super from the program block itself.

标签: oopsystem-verilog

解决方案


我担心与 c++ 不同,您的操作方式非常有限(就像在 java 中一样)。所以,所有的语言都是不同的。

与 java 类似,SystemVerilog 为您提供了可以在类成员中使用的关键字“super”。您将必须创建一个特定的类成员函数以在非类范围内访问其基(超)类成员:

class jaguar extends four_wheeler;
   ...

   function super_vehicle_type();
     super.vehicle_type();
  endfunction

endclass:jaguar

现在你可以使用

jaguar_h.super_vehicle_type();

您还可以在函数中使用类范围标识符来访问任何基类。

   function super_vehicle_type();
     four_wheeler::vehicle_type();
  endfunction

在上述情况下,您可以使用任何基类(而不是four_wheeler)作为类范围。


推荐阅读