Polymorphism in SystemVerilog
Polymorphism means many forms. Polymorphism in SystemVerilog provides an ability to an object to take on many forms.
Method handle of super-class can be made to refer to the subclass method, this allows polymorphism or different forms of the same method.
How, many forms of a method can be made by referring to the subclass method?
will see with an example,
Polymorphism example
Let’s write the base_class with a method display();
class base_class; virtual function void display(); $display("Inside base class"); endfunction endclass
Writing three extended classes of base_class, with display method overridden in it.
class ext_class_1 extends base_class; function void display(); $display("Inside extended class 1"); endfunction endclass class ext_class_2 extends base_class; function void display(); $display("Inside extended class 2"); endfunction endclass class ext_class_3 extends base_class; function void display(); $display("Inside extended class 3"); endfunction endclass
Create an object of each extended class,
ext_class_1 ec_1 = new(); ext_class_2 ec_2 = new(); ext_class_3 ec_3 = new();
Declare an array of a base class,
base_class b_c[3];
Assign extend class handles to base class handles.
b_c[0] = ec_1; b_c[1] = ec_2; b_c[2] = ec_3;
Call the display method using base_class handle,
b_c[0].display(); b_c[1].display(); b_c[2].display();
In the above method calls,
Though all the methods are called using base_class handle, different methods are getting called. this shows the many forms of the same method, this is called polymorphism.
Complete code,
// base class class base_class; virtual function void display(); $display("Inside base class"); endfunction endclass // extended class 1 class ext_class_1 extends base_class; function void display(); $display("Inside extended class 1"); endfunction endclass // extended class 2 class ext_class_2 extends base_class; function void display(); $display("Inside extended class 2"); endfunction endclass // extended class 3 class ext_class_3 extends base_class; function void display(); $display("Inside extended class 3"); endfunction endclass // module module class_polymorphism; initial begin //declare and create extended class ext_class_1 ec_1 = new(); ext_class_2 ec_2 = new(); ext_class_3 ec_3 = new(); //base class handle base_class b_c[3]; //assigning extended class to base class b_c[0] = ec_1; b_c[1] = ec_2; b_c[2] = ec_3; //accessing extended class methods using base class handle b_c[0].display(); b_c[1].display(); b_c[2].display(); end endmodule
Simulator Output
Inside extended class 1 Inside extended class 2 Inside extended class 3