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
design.sv
class Header;
    int id;

    function new(int id);
        this.id = id;
    endfunction
endclass
testbench.sv
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
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.