Polymorphism:

Polymorphism is the ability  to have the same code act differently based on the type of 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 the 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?

Similar Posts

3 Comments

  1. I guess in the above example, if we declared method as Virtual in Base Class as well as in Derived Class, the Base class print method will still point to the print method of Extended class, but I’m not completely sure about the reason behind it. Could you elaborate?

      1. Hi Hardik,
        Could you please explain the difference between declaring method in both base class and child class as virtual , v/s just declaring base class method virtual.

Comments are closed.