SystemVerilog Virtual Method

Virtual Methods in SystemVerilog

SystemVerilog Methods declared with the keyword virtual are referred to as virtual methods.

Virtual Methods,

  • Virtual Functions
  • Virtual Tasks

Virtual Functions

A function declared with a virtual keyword before the function keyword is referred to as virtual Function

Virtual Task

Task declared with a virtual keyword before the task keyword is referred to as virtual task

About Virtual Method

In a virtual method,
If the base_class handle is referring to the extended class, then the extended class method handle will get assigned to the base class handle.

In the below explanation, extended_class is an extended class of base_class.

base_class     b_c;
extended_class e_c;

Considering both the class’s has the method display().

assigning e_c to b_c,

b_c = e_c;

On calling b_c.display()

  • if display() method in base_class is virtual, then extended class display method will get called
  • if display() method in base_class is non-virtual, then base class display method will get called

Virtual function syntax

virtual function function_name;
  
  //Function definition
endfunction

Virtual task syntax

virtual task task_name;
  //task definition
endtask

Virtual Method Examples

Method without virtual keyword

In the below example,
the method inside the base class is declared without a virtual keyword, on calling method of the base class which is pointing to the extended class will call the base class method.

class base_class;
  
  function void display;
    $display("Inside base_class");
  endfunction
  
endclass
 
class extended_class extends base_class;
  
  function void display;
    $display("Inside extended class");
  endfunction
  
endclass

module virtual_class;
  initial begin
    base_class     b_c;
    extended_class e_c;
    
    e_c = new();
    b_c = e_c;
    
    b_c.display();
  end
endmodule

Simulator Output

Inside base_class

Click to execute on

A method with virtual keyword

In the below example,
the method inside the base class is declared with a virtual keyword, on calling method of the base class which is pointing to an extended class will call the extended class method.

class base_class;
  
  virtual function void display;
    $display("Inside base_class");
  endfunction
  
endclass
 
class extended_class extends base_class;
  
  function void display;
    $display("Inside extended_class");
  endfunction
  
endclass
 
module virtual_class;
  initial begin
    base_class     b_c;
    extended_class e_c;
    
    e_c = new();
    b_c = e_c;
    
    b_c.display();
  end
endmodule

Simulator Output

Inside extended_class

Click to execute on

❮ Previous Next ❯