POLYMORPHISM

Print

Polymorphism is the ability  to have the same code act differently based on the type of the Object that its being working with. This is a key topic of any Object Oriented Programming language. SystemVerilog enables 

Polymorphism in two ways: 

  1. Dynamic (Run-Time)

  2. Static (Compile-Time) 

Here we’ll discuss about Dynamic mode of Polymorphism which is supported via “Virtual Methods“.

Example: Without Virtual

class Base; 

  task print (); 

    $display("This is Base Class"); 

  endtask 

endclass 

 

class Extended extends Base; 

  task print (); 

    $display("This is Extended Class"); 

  endtask 

endclass 

 

program main; 

  Extended ext; 

  Base     ba; 

  

  initial 

    begin 

      ba = new(); 

      ba.print(); 

      

      ext = new(); 

      ba  = ext; 

      ba.print(); 

    end 

endprogram : main 


Example: With Virtual

class Base; 

  virtual task print (); 

    $display("This is Base Class"); 

  endtask 

endclass 

 

class Extended extends Base; 

  task print (); 

    $display("This is Extended Class"); 

  endtask 

endclass 

 

program main; 

  Extended ext; 

  Base     ba; 

  

  initial 

    begin 

      ba = new(); 

      ba.print(); 

      

      ext = new(); 

      ba  = ext; 

      ba.print(); 

    end 

endprogram : main


Here in both the examples just observe the above two outputs. Methods that are declared as virtual are executing the code in the object which is created. Most important is once we declared a Method as Virtual, it’s always Virtual in all derived classes. It means, we can not change the nature of the Method from Virtual to Non-Virtual in any of the derived classes. 

The methods which are added in the extended class which are not in the base class cannot be accessed using the base class handle. This will result in a compilation error. The compiler checks whether the method is existing in the base class definition or not. Now exercise for you guys that if we declared method as Virtual in Base Class as well as in Derived Class what will be the output you are observing and what’s the reason behind it?

Bạn Có Đam Mê Với Vi Mạch hay Nhúng      -     Bạn Muốn Trau Dồi Thêm Kĩ Năng

Mong Muốn Có Thêm Cơ Hội Trong Công Việc

Và Trở Thành Một Người Có Giá Trị Hơn

Bạn Chưa Biết Phương Thức Nào Nhanh Chóng Để Đạt Được Chúng

Hãy Để Chúng Tôi Hỗ Trợ Cho Bạn. SEMICON  

 

Last Updated ( Thursday, 27 May 2021 12:41 )