The super
keyword is used from within a sub-class to refer to properties and methods of the base class. It is mandatory to use the super
keyword to access properties and methods if they have been overridden by the sub-class.
Example
The super
keyword can only be used within a class scope that derives from a base class. The code shown below will have compilation errors because extPacket is not a child of Packet. Note that new
method is implicitly defined for every class definition, and hence we do not need a new
defintion in the base class Packet.
class Packet;
int addr;
function display ();
$display ("[Base] addr=0x%0h", addr);
endfunction
endclass
class extPacket; // "extends" keyword missing -> not a child class
function new ();
super.new ();
endfunction
endclass
module tb;
Packet p;
extPacket ep;
initial begin
ep = new();
p = new();
p.display();
end
endmodule
super.new ();
|
ncvlog: *E,CLSSPX (testbench.sv,12|8): 'super' can only be used within a class scope that derives from a base class.
Now let us see the output when extPacket is a derivative of class Packet.
class extPacket extends Packet; // extPacket is a child class of Packet
function new ();
super.new ();
endfunction
endclass
You can see from the simulation result below that there were no compilation errors.
ncsim> run
[Base] addr=0x0
ncsim: *W,RNQUIE: Simulation is complete.
Accessing base class methods
In the example shown below, display method of the base class is called from the display method of the child class using super
keyword.
class Packet;
int addr;
function display ();
$display ("[Base] addr=0x%0h", addr);
endfunction
endclass
class extPacket extends Packet;
function display();
super.display(); // Call base class display method
$display ("[Child] addr=0x%0h", addr);
endfunction
function new ();
super.new ();
endfunction
endclass
module tb;
Packet p;
extPacket ep;
initial begin
ep = new();
p = new();
ep.display();
end
endmodule
ncsim> run [Base] addr=0x0 [Child] addr=0x0 ncsim: *W,RNQUIE: Simulation is complete.