In Inheritance, we saw that methods invoked by a base class handle which points to a child class instance would eventually end up executing the base class method instead of the one in child class. If that function in the base class was declared as virtual, only then the child class method will be executed.

	bc = sc;
	bc.display (); 		// this calls the display() in Base Class and 
				// not the sub class as we might think

We'll use the same classes from previous session and do a comparison with and without virtual function.

Without virtual keyword
// Without declaring display() as virtual

class Packet;
   int addr;

   function new (int addr);
      this.addr = addr;

   function display ();
		$display ("[Base] addr=0x%0h", addr);

module tb;
   Packet bc;
   ExtPacket sc;

	initial begin
        sc = new (32'hfeed_feed, 32'h1234_5678);	

        bc = sc; 
		bc.display ();
Simulation Log
ncsim> run
[Base] addr=0xfeedfeed
ncsim: *W,RNQUIE: Simulation is complete.

Note that the base class display() function gets executed.

Login to your free account to read more ...

Was this article helpful ?