Wednesday, November 13, 2013

Polymorphism in SystemVerilog - good

Polymorphism in SystemVerilog

Many forms of the same Method based on the execution of the method at Run Time.

program test_poly;

  class shape;
    int width, height;
 
    function new(int x=0, int y=0);
      width  = x;
      height =y;
    endfunction //new

    virtual function area ();
      $display("From Shape Class");
    endfunction //area
  endclass //shape


  class rectangle extends shape;
    function new(int x=0, int y=0);
      super.new(x,y);
    endfunction //new

    function area();
      $display ("Rectangle area:width:%0d height:%0d ",width,height, width * height);
      return(width * height);
    endfunction //area
  endclass //rectangle

  class triangle extends shape;
    function new(int x=0, int y=0);
      super.new(x,y);
    endfunction //new

    function area();
      $display ("Triangle area:width:%0d height:%0d ",width,height, (width * height/2));
      return(width * height);
    endfunction //area
  endclass //triangle

  initial begin
    shape shape[2];
    rectangle rect1 = new(10,20);
    triangle  tria1 = new(10,20);

    shape[0] = rect1;
    shape[1] = tria1;

    shape[0].area();
    shape[1].area();

    #10; $display("Test End");
  end //initial

endprogram //test_poly

The program output as follows,

WITHOUT "virtual" keyword in 'area' function in 'shape' class
From Shape Class

From Shape Class

WITH "virtual" keyword in 'area' function in 'shape' class
Rectangle area:width:10 height:20         200
Triangle area:width:10 height:20         100

No comments:

Post a Comment