Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Copying Objects: Shallow Copy Example

SystemVerilog Classes & OOP

Runnable example from the SystemVerilog Copying Objects tutorial (Shallow Copy Example)

Open in IDE
testbench.sv
// 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
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.