Virtual methods in SystemVerilog are declared using the keyword "virtual"
before the method declaration.
There are two types of virtual methods:
1) Virtual functions
2) Virtual tasks.
Virtual Functions:
A function declared with the virtual keyword before the function keyword is
referred to as a virtual function.
Virtual functions allow polymorphic behavior, where the derived class can
override the implementation of the function defined in the base class.
Virtual function syntax:
virtual function return_type function_name;
// Function definition
endfunction
Virtual Tasks:
A task declared with the virtual keyword before the task keyword is referred to
as a virtual task. Similar to virtual functions, virtual tasks also support
polymorphism, allowing the derived class to provide its own implementation
of the task defined in the base class.
Virtual task syntax:
virtual task task_name;
// Task definition //
endtask
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
POLYMORPHISM
Polymorphism, which means "many forms," is a concept in SystemVerilog that allows an
object to take on multiple forms.
To achieve polymorphism we use virtual method in base class.
Here are the key points regarding polymorphism in SystemVerilog:
1. A parent class variable can be used to reference objects of child classes.
2. The parent class method should be declared as virtual.
3. The method name should be the same in both the parent and child classes.
4. Child class objects can be assigned to a parent class variable using the assignment
operator.
5. The child class methods can be accessed using the parent class handle.
Without virtual method in polymorphism
class parent;
bit [31:0] addr;
bit data;
function void display();
$display("Parent : addr=%0d data=%0d",addr,data);
endfunction
endclass
class child extends parent;
bit[31:0] addr;
int data;
function void display();
$display("Child : addr=%0d data=%0d",addr,data);
endfunction
endclass
module tb;
parent p;
child c;
initial
begin
p=new();
c=new();
p=c;
[Link]=3;
[Link]=4;
[Link]=5;
[Link]=8;
[Link]();
[Link]();
end
endmodule
# KERNEL: Parent : addr=3 data=0
# KERNEL: Child : addr=5 data=8
With virtual method in polymorphism
class parent;
bit [31:0] addr;
bit data;
virtual function void display();
$display("Parent : addr=%0d data=%0d",addr,data);
endfunction
endclass
class child extends parent;
bit[31:0] addr;
int data;
function void display();
$display("Child : addr=%0d data=%0d",addr,data);
endfunction
endclass
module tb;
parent p;
child c;
initial
begin
p=new();
c=new();
p=c;
[Link]=3;
[Link]=4;
[Link]=5;
[Link]=8;
[Link]();
[Link]();
end
endmodule
# KERNEL: Child : addr=5 data=8
# KERNEL: Child : addr=5 data=8
[Link]