The way I though polymorphism works was that when we call a method the simulator checks the class to see the function declaration. If the method is virtual the handler is checked to see which class type it holds (parent or extended) and execute the method inside that class type. If the method isn’t virtual it executes it without checking the class type.
class a;
virtual function display;
$display("a");
endfunction
endclass
class b extends a;
function display;
$display("b");
endfunction
endclass
class c extends b;
function display;
$display("c");
endfunction
endclass
module tb;
b hb;
c hc;
initial begin
hc = new();
hb = hc;
hb.display();
end
endmodule
The code above display “c” which doesn’t make sense to me since display is not virtual in class b so I expect it to display “b”. So what is wrong exactly in my understanding?
And if this is how it works, I don’t see the need to declare functions as virtual in extended classes so why should or shouldn’t we do so?
you need to remember: once virtual always virtual.
If you define some function virtual in any place of hierarchy, than it will be always viritual in other parts of hierarchy. No matter if we write virtual word for child functions.
In this example… can “c” grandchild directly access “a” method without parent “b” ? since super.display() will display parent “b” ?
I would like to get from class “c” method display only “a” and “c”, not “b”. How do we get that?
class a;
virtual function display;
$display("a");
endfunction
endclass
class b extends a;
function display;
$display("b");
endfunction
endclass
class c extends b;
function display;
$display("c");
endfunction
endclass