What is Inheritance? #
Inheritance is a fundamental concept in Object-Oriented Programming (OOP), and SystemVerilog fully supports it through class-based modeling. In simple terms, inheritance allows a class (called the child class) to automatically acquire the properties and behaviors (variables and methods) of another class (called the parent class or base class).
This promotes:
- Code reuse (don’t repeat what already exists)
- Hierarchy-based modeling (natural representation of relationships)
- Modularity and extensibility (easy to expand or override behavior)
Syntax:
class Parent;
// variables and methods
endclass
class Child extends Parent;
// additional variables and methods
endclass
Example:
class Animal;
function void speak();
$display("Animal makes sound");
endfunction
endclass
class Dog extends Animal;
function void bark();
$display("Dog barks");
endfunction
endclass
// Usage
module test;
initial begin
Dog d = new();
d.speak(); // Inherited from Animal
d.bark(); // Defined in Dog
end
endmodule
Output: Animal makes sound
Dog barks
Dog
inherits the speak()
method from Animal
, It can also define its own method like bark()
.
Overriding Parent Methods #
You can override a method in the child class using the same name.
class Animal;
function void speak();
$display("Animal speaks");
endfunction
endclass
class Cat extends Animal;
function void speak();
$display("Cat meows");
endfunction
endclass
// Usage
module test;
initial begin
Cat c = new();
c.speak();
end
endmodule
Now, calling speak()
from a Cat
object will run the child version, not the parent version.
Output: Cat meows
The super
Keyword #
If you still want to call the parent’s method that is overridden by the child class, use super
.
class Animal;
function void speak();
$display("Animal speaks");
endfunction
endclass
class Cat extends Animal;
function void speak();
super.speak(); // calling parent class method
$display("Cat meows");
endfunction
endclass
// Usage
module test;
initial begin
Cat c = new();
c.speak();
end
endmodule
Output: Animal speaks
Cat meows
Quick Summary #
Concept | Description |
---|---|
extends | Keyword to inherit a parent class |
Inherited Members | Child gets access to parent’s variables/functions |
Method Overriding | Child can redefine parent methods |
super | Used to call parent class functions/methods |