When you assign one class handle to another in SystemVerilog, you are not creating a new object — both handles point to the same memory. To get a truly independent copy, you need to understand the two copy strategies available: shallow copy and deep copy. Choosing the wrong one is a common source of hard-to-find bugs in verification environments.
11 min read | Intermediate Level
What You'll Learn
- How shallow copy works and why nested objects are not fully duplicated
- How to implement a deep copy function to get a fully independent object
- The key difference in behavior between shallow and deep copy
Background: Handles vs Objects
A SystemVerilog class variable is a handle — a reference (pointer) to an object stored in memory. When you write p2 = p1, you are copying the handle, not the object. Both p1 and p2 now point to the same object — modifying one modifies the other.
To create a new, separate object, you must use the new keyword — either with shallow copy syntax or a custom deep copy function.
Shallow Copy
Shallow copy creates a new object and copies all the direct members of the source object into it. You trigger it by passing an existing object handle to the new constructor:
Packet p1, p2;
p1 = new(32'hface_cafe, 32'h1234_5678, 26); // Create p1
p2 = new p1; // Shallow copy p1 into p2
This works correctly for primitive members like int, bit, and string — those values are copied by value into the new object. However, if the class contains a nested object (a member that is itself a class handle), shallow copy only copies the handle to that inner object, not the inner object itself.
This means both p1 and p2 will share the same nested object in memory. Changing the nested object through p1 will affect p2 too.
Shallow copy duplicates the top-level object but shares any nested objects between the original and the copy.
Shallow Copy Example
The Packet class below has two primitive members (addr, data) and one nested object (hdr of type Header):
// Nested class - represents a packet header
class Header;
int id;
function new(int id);
this.id = id;
endfunction
endclass
// Top-level class with a nested Header object
class Packet;
int addr;
int data;
Header hdr; // This is a handle to a Header object, not the object itself
function new(int addr, int data, int id);
hdr = new(id); // Create a Header object and store its handle
this.addr = addr;
this.data = data;
endfunction
function void display(string name);
$display("[%s] addr=0x%0h data=0x%0h id=%0d", name, addr, data, hdr.id);
endfunction
endclass
module tb;
Packet p1, p2;
initial begin
p1 = new(32'hface_cafe, 32'h1234_5678, 26);
p1.display("p1");
// Shallow copy: p2 gets its own addr and data, but shares p1's Header object
p2 = new p1;
p2.display("p2");
// Modify p1's primitive members AND its nested hdr.id
p1.addr = 32'habcd_ef12;
p1.data = 32'h5a5a_5a5a;
p1.hdr.id = 17; // This modifies the SHARED Header object
p1.display("p1");
// p2.addr and p2.data are unaffected (they were copied by value)
// but p2.hdr.id HAS changed - p2 shares the same Header object as p1
p2.display("p2");
end
endmodule
Output
[p1] addr=0xfacecafe data=0x12345678 id=26 [p2] addr=0xfacecafe data=0x12345678 id=26 [p1] addr=0xabcdef12 data=0x5a5a5a5a id=17 [p2] addr=0xfacecafe data=0x12345678 id=17
Look closely at the final line: p2.addr and p2.data kept their original values — those primitives were copied by value. But p2.hdr.id changed to 17, even though only p1.hdr.id was modified. This is because p2.hdr and p1.hdr point to the same Header object in memory.
Quick Check
Q: After a shallow copy, if you call p2.hdr = new(99) (creating a brand-new Header for p2), would that affect p1.hdr.id?
Show Answer
No. p2.hdr = new(99) creates a new Header object and points p2.hdr at it. p1.hdr still points to the original Header with its original id. The two handles are now fully independent. The problem occurs only when you modify fields of the shared object rather than replacing the handle itself.
Deep Copy
A deep copy creates a fully independent duplicate — including all nested objects. SystemVerilog has no built-in deep copy mechanism, so you implement it yourself as a custom copy() function inside the class.
The key difference from shallow copy: instead of just copying the nested handle, you copy the values inside the nested object, field by field.
class Packet;
int addr;
int data;
Header hdr;
function new(int addr, int data, int id);
hdr = new(id);
this.addr = addr;
this.data = data;
endfunction
// Deep copy: copy primitive fields AND nested object fields individually
function void copy(Packet p);
this.addr = p.addr;
this.data = p.data;
this.hdr.id = p.hdr.id; // Copy the value, not the handle
endfunction
function void display(string name);
$display("[%s] addr=0x%0h data=0x%0h id=%0d", name, addr, data, hdr.id);
endfunction
endclass
module tb;
Packet p1, p2;
initial begin
p1 = new(32'hface_cafe, 32'h1234_5678, 26);
p1.display("p1");
// Deep copy: p2 must already exist before calling copy()
p2 = new(1, 2, 3); // Create p2 with placeholder values
p2.copy(p1); // Deep copy p1's contents into p2
p2.display("p2");
// Modify p1 including the nested hdr.id
p1.addr = 32'habcd_ef12;
p1.data = 32'h5a5a_5a5a;
p1.hdr.id = 17;
p1.display("p1");
// p2 is now fully independent - none of its fields change
p2.display("p2");
end
endmodule
Output
[p1] addr=0xfacecafe data=0x12345678 id=26 [p2] addr=0xfacecafe data=0x12345678 id=26 [p1] addr=0xabcdef12 data=0x5a5a5a5a id=17 [p2] addr=0xfacecafe data=0x12345678 id=26
This time p2.hdr.id stays at 26 after p1.hdr.id is updated to 17. The two Header objects are independent — copy() transferred the value of id rather than the handle to the same object.
Before calling copy(), p2 must already be a valid, constructed object. The copy() function writes into the existing p2.hdr object — if p2.hdr is still null, it will cause a null pointer error at runtime.
Shallow vs Deep Copy — Side-by-Side
| Property | Shallow Copy (new p1) | Deep Copy (custom copy()) |
|---|---|---|
Primitive fields (int, bit) | Copied independently | Copied independently |
| Nested object fields | Handle shared - same object | Values copied - separate object |
| Syntax | p2 = new p1 | p2 = new(...); p2.copy(p1) |
| Built-in support | Yes | No - must implement manually |
| Modification isolation | Partial (primitives only) | Full |
Where Is Object Copying Used?
In verification environments, transactions are often generated by a sequencer and passed to multiple components (scoreboard, coverage collector, driver). Each component needs its own independent copy of the transaction so that modifications in one component do not corrupt the data seen by others. Deep copy functions are standard practice in UVM transaction classes for exactly this reason.
Common Beginner Mistakes
Mistake #1: Expecting shallow copy to fully isolate nested objects
Writing p2 = new p1 and then modifying p1.hdr.id will also change p2.hdr.id, because both handles point to the same Header object. Why? Shallow copy only duplicates the top-level object — use a deep copy function whenever nested objects must be independent.
Mistake #2: Calling copy() before constructing the destination object
The copy() function writes into an existing object's nested members. Why? Writing p2.copy(p1) without first creating p2 (and its internal hdr) causes a null handle dereference error at runtime — always construct the destination first: p2 = new(...); p2.copy(p1);
Mistake #3: Using handle assignment instead of copy
Writing p2 = p1 does not create a new object — it makes p2 an alias for the same object. Why? Any change through either handle modifies the single underlying object — if independent copies are actually needed, this plain assignment is never the right tool.
Practice Exercise
Challenge: Add Deep Copy for a Two-Level Nested Class
Extend the example so that Header itself contains a nested object — a SubHeader class with a field priority_level. Update the copy() function in Packet to perform a complete deep copy of all three levels.
Hint
Your copy() function needs to reach two levels deep: this.hdr.sub.priority_level = p.hdr.sub.priority_level. Alternatively, add a copy() method to Header as well and call it from Packet.copy().
Solution
class SubHeader;
int priority_level;
function new(int p); this.priority_level = p; endfunction
endclass
class Header;
int id;
SubHeader sub;
function new(int id, int pri);
this.id = id;
sub = new(pri);
endfunction
// Copy all fields including the nested SubHeader
function void copy(Header h);
this.id = h.id;
this.sub.priority_level = h.sub.priority_level;
endfunction
endclass
class Packet;
int addr;
int data;
Header hdr;
function new(int addr, int data, int id, int pri);
hdr = new(id, pri);
this.addr = addr;
this.data = data;
endfunction
function void copy(Packet p);
this.addr = p.addr;
this.data = p.data;
this.hdr.copy(p.hdr); // Delegate nested copy to Header's copy()
endfunction
function void display(string name);
$display("[%s] addr=0x%0h data=0x%0h id=%0d pri=%0d",
name, addr, data, hdr.id, hdr.sub.priority_level);
endfunction
endclass
Delegating this.hdr.copy(p.hdr) to Header's own copy() method — rather than reaching directly into hdr.sub.priority_level from within Packet — keeps each class responsible for copying its own fields, and cascades cleanly no matter how many levels deep the nesting goes.
Summary
In this tutorial, you learned:
- Shallow copy (
p2 = new p1) copies primitive fields by value but shares nested object handles between the original and the copy - Modifications to a nested object through the original will be visible through the shallow copy, because both handles point to the same memory
- Deep copy requires a custom
copy()function that explicitly copies the fields of each nested object rather than the handle - The destination object must be fully constructed before calling
copy()to avoid null handle errors
The this keyword is used to refer to class properties, parameters, and methods of the current instance. It can only be used within non-static methods, constraints, and covergroups — it's essentially a pre-defined object handle that refers to whatever object was used to invoke the method (or constraint, or covergroup) that this appears inside.
7 min read | Intermediate Level
What You'll Learn
- What
thisrefers to, and where it's allowed to be used - Why
thisis needed specifically when a local name shadows a class property - How
thisshows up inside a constraint block and a covergroup, not just inside a method - Why
thisisn't needed most of the time
The Classic Case: A Shadowed Constructor Argument
The most common reason to reach for this is inside a constructor whose argument shares a name with the class property it's meant to initialize:
class Packet;
bit [31:0] addr;
function new (bit [31:0] addr);
// addr = addr; // Which addr should get assigned ?
this.addr = addr; // addr variable in Packet class should be
// assigned with local variable addr in new()
endfunction
endclass
module tb;
initial begin
Packet pkt = new (32'hdead_beef);
$display ("addr=0x%0h", pkt.addr);
end
endmodule
Output
addr=0xdeadbeef
The commented-out line, addr = addr;, is genuinely ambiguous: inside the constructor's own scope, the local argument addr shadows the class property of the same name, so a plain addr = addr; would just assign the local argument to itself — doing nothing useful, and leaving the class's own addr property untouched at its default value. this.addr = addr; resolves the ambiguity explicitly: this.addr always means the class property, regardless of what local names happen to exist in the same scope.
Quick Check
Q: If the constructor's argument were named new_addr instead of addr, would this still be necessary?
Show Answer
No — not strictly. With no naming collision, a plain addr = new_addr; unambiguously assigns the class property, since there's no local variable also called addr competing for that name. this only becomes necessary once a local name actually shadows a class property.
Using this Inside a Constraint Block
this is also legal inside a constraint block, referring to the enclosing object's own properties:
class Packet;
rand bit [7:0] addr;
rand bit [7:0] data;
constraint c_order { this.addr < this.data; }
endclass
Unlike a constructor, a constraint block doesn't take its own list of arguments, so there's usually no competing local name to shadow a property in the first place — this here is legal but rarely strictly necessary; addr < data; would resolve identically in this specific case.
Using this Inside a Covergroup
The same applies inside a covergroup declared within a class:
class Packet;
rand bit [7:0] addr;
covergroup cg;
coverpoint this.addr;
endgroup
function new ();
cg = new ();
endfunction
endclass
this.addr explicitly refers to the class property, exactly the same way it would inside a method — and, just like inside a constraint block, it's legal here even without a naming collision forcing the issue.
Quick Check
Q: Why is this generally less necessary inside a constraint block or covergroup than inside a constructor?
Show Answer
Because neither a constraint block nor a covergroup has its own separate list of local arguments the way a constructor does — there's usually nothing competing with a class property for the same name in those contexts, so the disambiguation this provides isn't often actually needed there, even though the syntax is perfectly legal.
Where Is this Used?
Constructor argument shadowing, exactly like the addr example above, is extremely common throughout UVM base classes and any hand-written testbench class — it's standard practice to name a constructor's arguments after the properties they initialize, which makes this a routine, expected part of almost every non-trivial class's constructor.
Common Beginner Mistakes
Mistake #1: Forgetting this when an argument shadows a class property
As the commented-out line in the first example shows, addr = addr; silently does nothing useful when the local argument shadows the class property. Why? This compiles without any error or warning, so the bug — a property that's silently never assigned — can go unnoticed until something downstream reads that property and gets an unexpected default value.
Mistake #2: Assuming this is required everywhere inside a class
As the Quick Check above shows, this is only actually needed when a local name genuinely shadows a class property. Why? Using it everywhere out of habit isn't wrong, just unnecessary verbosity — most method bodies with no naming collisions don't need it at all.
Mistake #3: Trying to use this inside a static method
this can only be used inside non-static methods, constraints, and covergroups. Why? A static method isn't tied to any one specific object — it can be called without an object even existing yet — so there's no "current instance" for this to refer to. See SystemVerilog Static Variables & Functions for more on that distinction.
Practice Exercise
Challenge: Fix a Shadowed Setter
Write a class Config with a property mode, and a method set_mode(bit [1:0] mode) whose argument shares a name with the property. Use this to assign it correctly, then verify with a small testbench.
Hint
Follow the exact same pattern as the constructor example — this.mode = mode; inside the method body.
Solution
class Config;
bit [1:0] mode;
function void set_mode (bit [1:0] mode);
this.mode = mode;
endfunction
endclass
module tb;
initial begin
Config cfg = new ();
cfg.set_mode (2'b10);
$display ("mode=0x%0h", cfg.mode);
end
endmodule
This prints mode=0x2. Without this, mode = mode; inside set_mode() would just assign the local argument to itself, leaving cfg.mode at its default value of 0 instead.
Summary
In this tutorial, you learned:
thisrefers to the current object instance, and can be used inside non-static methods, constraints, and covergroups- It's needed specifically when a local name (like a constructor or method argument) shadows a class property of the same name
- Without
thisin a shadowed case, an assignment likeaddr = addr;silently does nothing useful, rather than raising an error thisis legal inside constraint blocks and covergroups too, though it's rarely strictly necessary there, since neither has its own separate list of local arguments the way a constructor doesthiscannot be used inside a static method, since a static method isn't tied to any specific object
Each class instance normally has its own independent copy of every internal variable and its own separate calls to every method. SystemVerilog's static keyword changes that default for a specific property or method — letting you share a single copy across every instance of a class instead, or call a method without ever needing an object at all.
10 min read | Intermediate Level
What You'll Learn
- The default behavior: every class instance gets its own independent copy of each property
- How a
staticproperty becomes one shared copy across every instance instead - What a
staticmethod can and can't access, compared to a regular method - Why a
staticmethod can never access a non-static (per-instance) member
The Default: Each Instance Gets Its Own Copy
Before introducing static, here's the default behavior it changes — each class instance holding its own independent copy of every internal variable:
class Packet;
bit [15:0] addr;
bit [7:0] data;
function new (bit [15:0] ad, bit [7:0] d);
addr = ad;
data = d;
$display ("addr=0x%0h data=0x%0h", addr, data);
endfunction
endclass
module tb;
initial begin
Packet p1, p2, p3;
p1 = new (16'hdead, 8'h12);
p2 = new (16'hface, 8'hab);
p3 = new (16'hcafe, 8'hfc);
end
endmodule
Each of the class objects p1, p2, p3 has its own addr and data — changing one has no effect on the others.
Output
ncsim> run addr=0xdead data=0x12 addr=0xface data=0xab addr=0xcafe data=0xfc ncsim: *W,RNQUIE: Simulation is complete.
Static Variables
When a variable inside a class is declared static, that variable becomes the only copy shared across every instance of the class. To demonstrate, here's a static counter compared against a normal (non-static) counter, both incremented inside new() so they update every time an object is created:
class Packet;
bit [15:0] addr;
bit [7:0] data;
static int static_ctr = 0;
int ctr = 0;
function new (bit [15:0] ad, bit [7:0] d);
addr = ad;
data = d;
static_ctr++;
ctr++;
$display ("static_ctr=%0d ctr=%0d addr=0x%0h data=0x%0h", static_ctr, ctr, addr, data);
endfunction
endclass
module tb;
initial begin
Packet p1, p2, p3;
p1 = new (16'hdead, 8'h12);
p2 = new (16'hface, 8'hab);
p3 = new (16'hcafe, 8'hfc);
end
endmodule
Output
ncsim> run static_ctr=1 ctr=1 addr=0xdead data=0x12 static_ctr=2 ctr=1 addr=0xface data=0xab static_ctr=3 ctr=1 addr=0xcafe data=0xfc ncsim: *W,RNQUIE: Simulation is complete.
static_ctr is shared between p1, p2, and p3, so it climbs to 3 as each new packet is created. ctr, on the other hand, is not static, so every object gets its own fresh copy — each one starts at 0 and is incremented exactly once inside its own constructor, which is why ctr shows 1 for every single object, never climbing higher.
Declaring a variable static is useful whenever you need to know the total number of objects (like packets) created so far, across the entire testbench, rather than just within one specific object.
Quick Check
Q: If a fourth object, p4, were created right after this code, what would static_ctr and ctr show for it?
Show Answer
static_ctr = 4, ctr = 1. static_ctr keeps counting up across every object ever created, while ctr always starts fresh at 0 for a brand new object and gets incremented exactly once in its own constructor call, landing on 1 every time.
Static Functions
A static method follows all the usual class scoping and access rules, with one key difference: it can be called even without any object of the class ever being instantiated. A static method has no access to non-static (per-instance) members, but it can directly access static class properties or call other static methods of the same class. Calling a static method by class name uses the scope resolution operator :::
class Packet;
static int ctr=0;
function new ();
ctr++;
endfunction
static function get_pkt_ctr ();
$display ("ctr=%0d", ctr);
endfunction
endclass
module tb;
Packet pkt [6];
initial begin
for (int i = 0; i < $size(pkt); i++) begin
pkt[i] = new;
end
Packet::get_pkt_ctr(); // Static call using :: operator
pkt[5].get_pkt_ctr(); // Normal call using instance
end
endmodule
Output
ncsim> run ctr=6 ctr=6 ncsim: *W,RNQUIE: Simulation is complete.
Both calls — Packet::get_pkt_ctr() and pkt[5].get_pkt_ctr() — print the exact same value, because there's only one shared ctr regardless of which syntax is used to reach it. Calling a static method through a specific instance doesn't give it any special access to that instance's own data — it's still the same static method operating on the same shared state either way.
Now let's add a non-static member called mode and try to reference it from the static function:
class Packet;
static int ctr=0;
bit [1:0] mode;
function new ();
ctr++;
endfunction
static function get_pkt_ctr ();
$display ("ctr=%0d mode=%0d", ctr, mode);
endfunction
endclass
This isn't allowed, and results in a compile-time error:
$display ("ctr=%0d mode=%0d", ctr, mode);
|
ncvlog: *E,CLSNSU (static-function.sv,10|40): A static class method cannot access non static class members.
This makes sense once you consider that a static method can be called with no object ever having been created — get_pkt_ctr() has no specific instance to pull mode from, since mode only exists once an actual object exists to hold it.
A static method can never be declared virtual either — the same restriction covered for constructors in SystemVerilog Class Constructor. Virtual dispatch depends on an object's actual runtime type, but a static method call may not even involve an object at all.
Quick Check
Q: Could get_pkt_ctr() call a different static method of the same class from inside itself?
Show Answer
Yes. A static method can freely access static properties and call other static methods of the same class — the restriction is specifically about non-static (per-instance) members, not about static methods calling each other.
Where Are Static Variables Used?
A shared static counter is a common way to track a running total across an entire test — for example, the total number of transactions generated so far by every generator instance combined, rather than just one specific generator's own count.
Common Beginner Mistakes
Mistake #1: Assuming every property is shared across instances by default
As the first example shows, the default behavior is the opposite — every property gets its own independent copy per object. Why? Only properties explicitly declared static are shared; everything else follows the normal one-copy-per-object rule.
Mistake #2: Trying to access a non-static member from inside a static method
As the mode example shows, this is a compile-time error. Why? A static method can be called with no object ever created, so it has no specific instance to resolve a non-static member against — there's simply nothing for mode to mean in that context.
Mistake #3: Assuming instance-based and class-based static calls behave differently
Packet::get_pkt_ctr() and pkt[5].get_pkt_ctr() produce identical results. Why? A static method operates on shared class-level state regardless of the syntax used to call it — calling it "through" a specific object doesn't give it any special access to that object's own data.
Mistake #4: Declaring a static method as virtual
This isn't allowed, for the same reason a constructor can't be virtual. Why? Virtual dispatch depends on resolving a call based on an actual object's runtime type, but a static method call doesn't necessarily involve any object at all.
Practice Exercise
Challenge: Track a Running Byte Total
Extend the Packet class with a static int total_bytes = 0; property, incremented in the constructor by however many bytes each packet's data field represents (assume 1 byte per packet, for simplicity). Add a static function called report() that prints the total number of packets created and the total bytes across all of them.
Hint
Follow the same pattern as static_ctr — increment total_bytes inside the constructor, alongside the existing counter.
Solution
class Packet;
bit [15:0] addr;
bit [7:0] data;
static int static_ctr = 0;
static int total_bytes = 0;
function new (bit [15:0] ad, bit [7:0] d);
addr = ad;
data = d;
static_ctr++;
total_bytes++; // 1 byte per packet, for simplicity
endfunction
static function report ();
$display ("Packets created: %0d, Total bytes: %0d", static_ctr, total_bytes);
endfunction
endclass
module tb;
initial begin
Packet p1, p2, p3;
p1 = new (16'hdead, 8'h12);
p2 = new (16'hface, 8'hab);
p3 = new (16'hcafe, 8'hfc);
Packet::report ();
end
endmodule
This prints Packets created: 3, Total bytes: 3. Both static_ctr and total_bytes are shared across every Packet object, so report() can summarize the entire run without needing a reference to any specific packet at all.
Summary
In this tutorial, you learned:
- By default, every class instance gets its own independent copy of each property
- A property declared
staticbecomes one shared copy across every instance of the class instead - A static method can be called even with no object created, using
ClassName::method_name(), and behaves identically whether called that way or through a specific instance - A static method can never access non-static members, and can never be declared
virtual - A shared static counter is a common way to track a running total across an entire testbench, independent of any one specific object
A constructor is simply a method used to create a new object of a particular class data type. C/C++ requires complex memory allocation techniques, and improper de-allocation there can lead to memory leaks and other behavioral issues. SystemVerilog, although not a general-purpose programming language, handles object construction simply and provides automatic garbage collection — you never have to manually free a class object yourself.
9 min read | Intermediate Level
What You'll Learn
- What a constructor is, and what happens if you don't write one yourself
- How constructor chaining works between a base and derived class via
super.new() - Why a constructor can never be declared
virtualorstatic - How a "typed constructor" lets you construct a subclass object directly into a base-class handle
Explicitly Defining a Constructor
// Define a class called "Packet" with a 32-bit variable to store address
// Initialize "addr" to 32'hfade_cafe in the new function, also called constructor
class Packet;
bit [31:0] addr;
function new ();
addr = 32'hfade_cafe;
endfunction
endclass
module tb;
// Create a class handle called "pkt" and instantiate the class object
initial begin
// The class's constructor new() fn is called when the object is instantiated
Packet pkt = new;
// Display the class variable - Because constructor was called during
// instantiation, this variable is expected to have 32'hfade_cafe;
$display ("addr=0x%0h", pkt.addr);
end
endmodule
Declaring pkt and calling new creates an object of class Packet and automatically calls the new() function inside the class. new() is the class constructor — a way to initialize class variables with some value. It has no return type, and it's non-blocking (no time-consuming statements allowed inside it).
Output
ncsim> run addr=0xfadecafe ncsim: *W,RNQUIE: Simulation is complete.
Quick Check
Q: If function new(int val); required an argument with no default value, what would Packet pkt = new; (called with no arguments) do?
Show Answer
It would fail to compile. A constructor argument with no default value is required at every call site — calling new without supplying it is a compile-time error, the same as calling any other function with a missing required argument.
The Implicit Constructor
If a class doesn't define its own new() function, SystemVerilog automatically provides one. Every property then gets its type's own default value — here, addr initializes to zero, since that's the default for bit:
// Define a simple class with a variable called "addr"
// Note that the new() function is not defined here
class Packet;
bit [31:0] addr;
endclass
module tb;
// When the class object is instantiated, then the constructor is
// implicitly defined by the tool and called
initial begin
Packet pkt = new;
$display ("addr=0x%0h", pkt.addr);
end
endmodule
Output
ncsim> run addr=0x0 ncsim: *W,RNQUIE: Simulation is complete.
Constructor Chaining in Inherited Classes
A derived class's new() method typically calls its parent class's constructor first, using super.new(). Once the base class constructor completes, each property defined in the derived class gets its own default value, and only then does the rest of the derived class's new() method run:
// Define a simple class and initialize the class member "data" in new() function
class baseClass;
bit [15:0] data;
function new ();
data = 16'hface;
endfunction
endclass
// Define a child class extended from the above class with more members
// The constructor new() function accepts a value as argument, and by default is 2
class subClass extends baseClass;
bit [3:0] id;
bit [2:0] mode = 3;
function new (int val = 2);
// The new() function in child class calls the new function in
// the base class using the "super" keyword
super.new ();
// Assign the value obtained through the argument to the class member
id = val;
endfunction
endclass
module tb;
initial begin
// Create two handles for the child class
subClass sc1, sc2;
// Instantiate the child class and display member variable values
sc1 = new ();
$display ("data=0x%0h id=%0d mode=%0d", sc1.data, sc1.id, sc1.mode);
// Pass a value as argument to the new function in this case and print
sc2 = new (4);
$display ("data=0x%0h id=%0d mode=%0d", sc2.data, sc2.id, sc2.mode);
end
endmodule
The order of operations here is: subClass's new() starts, immediately calls super.new(), baseClass's constructor runs to completion (setting data), control returns to subClass, its own properties get their declared or default values (mode = 3), and finally the rest of subClass's constructor body runs (id = val).
Output
ncsim> run data=0xface id=2 mode=3 data=0xface id=4 mode=3 ncsim: *W,RNQUIE: Simulation is complete.
Quick Check
Q: If subClass's constructor didn't explicitly call super.new() at all, would sc1.data still show 0xface?
Show Answer
Yes, in this specific case. Since baseClass's constructor takes no required arguments, SystemVerilog implicitly calls it automatically at the start of the derived class's constructor even if you never write super.new() yourself. This only breaks down if the base constructor requires an argument with no default — then an explicit super.new(...) becomes mandatory.
Why a Constructor Can't Be virtual or static
A constructor can be declared local or protected (see SystemVerilog local vs protected for what those restrict), but never static or virtual:
class ABC;
string fruit;
// Note that the constructor is defined as "virtual" which is not allowed
// in SystemVerilog. Class constructor cannot be "static" either
virtual function new ();
fruit = "Apple";
endfunction
endclass
// Instantiate the class object and print its contents
module tb;
initial begin
ABC abc = new();
$display ("fruit = %s", abc.fruit);
end
endmodule
Output
virtual function new ();
|
ncvlog: *E,BADQAL (testbench.sv,6|21): Lifetime or qualifier(s) 'virtual' not allowed before function new declaration.
Typed Constructors
You can call a subclass's new() function and assign the result directly to a handle of the base class, all in a single statement, by referencing the subclass's constructor with the scope resolution operator :::
class C;
endclass
class D extends C;
endclass
module tb;
initial begin
C c = D::new;
end
endmodule
c, a handle of base class C, now references a newly constructed object of type D. This achieves the exact same effect as the more verbose two-step version below:
module tb;
initial begin
D d = new;
C c = d;
end
endmodule
Quick Check
Q: After C c = D::new;, is c an object of type C, or type D?
Show Answer
Type D. The typed constructor built an actual D object — c is just a base-class-typed handle pointing to it. This is exactly the same distinction covered in SystemVerilog Class Handle: the handle's declared type and the object it actually points to don't have to match, as long as the object's type is compatible with (here, derived from) the handle's type.
Where Is This Used?
Typed constructors are handy in factory-style code, where you want to build a specific derived object but store or pass it around using a common base-class handle — exactly the pattern UVM's own factory mechanism is built on, letting a testbench create objects of a specific type while working with them generically through their base class interface.
Common Beginner Mistakes
Mistake #1: Assuming properties start as garbage without an explicit constructor
As the implicit constructor example shows, an object's properties still get well-defined values — the type's own default (like 0 for numeric types) — even with no new() written at all. Why? SystemVerilog always provides an implicit constructor if you don't write your own, so properties are never left in an undefined or garbage state.
Mistake #2: Declaring a constructor as virtual or static
Both are illegal on function new(), and produce a compile-time error. Why? A constructor's job is to build one specific object; the language simply doesn't allow the virtual or static qualifiers on it, even though local and protected are both fine.
Mistake #3: Assuming a derived class's own properties are set before the base constructor runs
It's the opposite order. Why? super.new() runs the base class's constructor to completion first; only after that do the derived class's own properties get their default or declared values, followed by the rest of the derived constructor's body.
Mistake #4: Confusing a typed constructor with a later handle reassignment
C c = D::new; actually constructs the object as type D, in one step — it's not the same as constructing a C and reassigning it later. Why? The distinction matters for polymorphism: c behaves as a genuine D object underneath, even though its declared handle type is C.
Practice Exercise
Challenge: Three Levels of Constructor Chaining
Extend the baseClass/subClass example with a third class, grandchildClass, that extends subClass and adds its own property tag (default value 7). Its constructor should call super.new() and accept its own argument for id. Predict what data, id, mode, and tag will show when constructed with no arguments.
Hint
The chain now runs three levels deep: grandchildClass::new() calls super.new() (which is subClass::new()), which itself calls super.new() (which is baseClass::new()) — each one completes fully before control returns to the level that called it.
Solution
class grandchildClass extends subClass;
bit [3:0] tag = 7;
function new (int val = 2);
super.new (val);
endfunction
endclass
module tb;
initial begin
grandchildClass gc;
gc = new ();
$display ("data=0x%0h id=%0d mode=%0d tag=%0d", gc.data, gc.id, gc.mode, gc.tag);
end
endmodule
data=0xface id=2 mode=3 tag=7. baseClass::new() sets data; back in subClass::new(), mode gets its default and id is set from val (defaulting to 2); back in grandchildClass::new(), tag gets its own default of 7 — the same base-first, then-each-level ordering, just extended one level further.
Summary
In this tutorial, you learned:
- A constructor (
new()) initializes a class object's properties when it's created, and has no return type - If a class defines no constructor of its own, SystemVerilog provides an implicit one, and every property gets its type's default value
- A derived class's constructor calls its base class's constructor via
super.new(), which runs to completion before the derived class's own properties are initialized - A constructor can be
localorprotected, but nevervirtualorstatic - A typed constructor (
C c = D::new;) builds a subclass object and assigns it directly to a base-class handle in one statement
Sometimes the compiler errors out because a class variable is used before the declaration of the class itself. This happens when two classes need a handle to each other — the classic chicken-and-egg puzzle. It occurs because the compiler processes the first class it encounters, and finds a reference to a second class that hasn't been declared yet.
9 min read | Intermediate Level
What You'll Learn
- Why two classes referencing each other creates a "used before declared" compile error
- How a
typedefforward declaration resolves it - How to build a complete example where two classes actually hold and use handles to each other
- How the same forward-declaration technique applies to parameterized classes
The Problem: A Chicken-and-Egg Reference
class ABC;
DEF def; // Error: DEF has not been declared yet
endclass
class DEF;
ABC abc;
endclass
Output
file: typdef-class.sv
DEF def;
|
ncvlog: *E,NOIPRT (typedef-class.sv,2|5): Unrecognized declaration 'DEF' could be an unsupported keyword, a spelling mistake or missing instance port list '()' [SystemVerilog].
ABC references DEF before DEF has been declared anywhere in the file — the compiler has no way to know DEF is a class at this point.
The Fix: Forward Declaration With typedef
A forward declaration using typedef tells the compiler that a class definition will be found later in the same file:
typedef class DEF; // Inform compiler that DEF might be
// used before actual class definition
class ABC;
DEF def; // Okay: Compiler knows that DEF
// declaration will come later
endclass
class DEF;
ABC abc;
endclass
By using typedef, DEF is declared to be of type class, which is later confirmed once its actual definition appears. It isn't necessary to specify that DEF is of type class in the typedef statement:
typedef DEF; // Legal
class ABC;
DEF def;
endclass
Quick Check
Q: Would typedef class DEF; still work if it were placed after class ABC instead of before it?
Show Answer
No. The compiler processes a file top to bottom, and ABC references DEF while being read — the forward declaration has to appear before the first place DEF is actually referenced, not just before DEF's own full definition.
A Complete Working Example
Here's the forward-declaration pattern actually put to use — ABC holds a handle to a DEF object and reads a value from it:
typedef class DEF;
class ABC;
DEF def;
int val = 10;
function new (DEF d);
def = d;
endfunction
function void show ();
$display ("ABC.val=%0d, DEF.val=%0d", val, def.val);
endfunction
endclass
class DEF;
ABC abc;
int val = 20;
endclass
module tb;
initial begin
DEF d = new ();
ABC a = new (d);
a.show ();
end
endmodule
This prints ABC.val=10, DEF.val=20. d (a DEF object) is constructed first, then passed into ABC's constructor, which stores the handle. a.show() then reads its own val directly and def.val through the stored DEF handle — exactly the kind of cross-referencing the forward declaration exists to make possible.
Quick Check
Q: What would happen if ABC a = new(d); were changed to ABC a = new(null); instead?
Show Answer
The code would still compile fine, but a.show() would fail at run time with a null pointer dereference when it tries to read def.val — def would still be null, with no actual DEF object behind it. See SystemVerilog Class Handle for more on this exact failure mode.
Forward-Declaring a Parameterized Class
A typedef forward declaration also works for a class with a parameterized port list:
typedef XYZ;
module top;
XYZ #(8'h3f, real) xyz0; // positional parameter override
XYZ #(.ADDR(8'h60), .T(real)) xyz1; // named parameter override
endmodule
class XYZ #(parameter ADDR = 8'h00, type T = int);
endclass
Exactly like the non-parameterized case, XYZ is used (with parameter overrides) inside top before its actual definition appears later in the file.
Where Is This Used?
In verification environments, a driver and a monitor — or a sequencer and a scoreboard — sometimes need mutual handles to each other for tighter coordination, without one component being defined strictly "before" the other in the file. A typedef forward declaration is exactly what makes that legal, regardless of which class happens to be written first.
Common Beginner Mistakes
Mistake #1: Forgetting the forward declaration entirely
As the first example shows, referencing a class before it's declared anywhere is always a compile-time error. Why? Two mutually-referencing classes can't simply be reordered to fix this — whichever one is written first will always reference the other before it's been declared, which is exactly the case a forward declaration solves.
Mistake #2: Placing the typedef after the reference that needs it
As the first Quick Check shows, the forward declaration has to come before its first use, not just somewhere earlier in the file. Why? The compiler processes declarations in order, so a typedef placed too late doesn't help the reference that appears before it.
Mistake #3: Assuming typedef alone is a complete class definition
typedef class DEF; is only a promise that a real class definition will appear later — it isn't a substitute for one. Why? If the actual class DEF; ... endclass definition is never provided anywhere in the same compilation scope, that's still a compile error, just a different one.
Mistake #4: Assuming a null handle behaves like a valid, empty object
As the second Quick Check shows, passing null where a real object is expected compiles fine but fails at run time the moment a member is accessed through it. Why? A forward-declared type still follows all the same handle rules as any other class — it's still null until something actually constructs an object and assigns it.
Practice Exercise
Challenge: A Driver and Monitor That Reference Each Other
Using the same forward-declaration pattern, write two classes, Driver and Monitor, each holding a handle to the other. Give Driver a property tx_count and Monitor a property rx_count, and write a Monitor method that prints both counts by reading its own rx_count and the connected Driver's tx_count.
Hint
Follow the exact same structure as the ABC/DEF example — forward-declare whichever class is referenced first, then have one constructor accept and store a handle to the other.
Solution
typedef class Driver;
class Monitor;
Driver drv;
int rx_count = 5;
function new (Driver d);
drv = d;
endfunction
function void report ();
$display ("rx_count=%0d, tx_count=%0d", rx_count, drv.tx_count);
endfunction
endclass
class Driver;
Monitor mon;
int tx_count = 7;
endclass
module tb;
initial begin
Driver d = new ();
Monitor m = new (d);
m.report ();
end
endmodule
This prints rx_count=5, tx_count=7 — the same cross-referencing pattern as ABC/DEF, just with names that reflect how this shows up in an actual testbench.
Summary
In this tutorial, you learned:
- Two classes referencing each other creates a "used before declared" compile error, since the compiler processes declarations in order
typedef class ClassName;forward-declares a class, telling the compiler its full definition will appear later in the same file- The forward declaration must appear before the class's first reference, not just somewhere earlier in the file
- The
classkeyword in thetypedefstatement is optional —typedef ClassName;works too - The same technique applies to parameterized classes, letting them be referenced (with parameter overrides) before their full definition appears
Quiz
No quiz questions available for this article.