SystemVerilog OOP Mastery · All levels
No Operator Overloading: Code Examples
Code Examples for No Operator Overloading.
Code examples
Value object math: overloaded operators vs explicit methods
systemverilog
// C++: operator overloading
class Vec2 {
public:
int x, y;
Vec2(int ax, int ay) : x(ax), y(ay) {}
Vec2 operator+(const Vec2& rhs) const { return Vec2(x + rhs.x, y + rhs.y); }
bool operator==(const Vec2& rhs) const { return x == rhs.x && y == rhs.y; }
};
Vec2 c = Vec2(1, 2) + Vec2(3, 4);
bool same = (c == Vec2(4, 6));
// SystemVerilog: explicit methods
class vec2;
int x, y;
function new(int ax = 0, int ay = 0);
x = ax;
y = ay;
endfunction
function vec2 add(vec2 rhs);
return new(x + rhs.x, y + rhs.y);
endfunction
function bit equals(vec2 rhs);
return (x == rhs.x) && (y == rhs.y);
endfunction
endclass
vec2 c_sv = new(1, 2);
c_sv = c_sv.add(new(3, 4));
if (c_sv.equals(new(4, 6))) $display("match");C++ lets objects participate directly in expressions. SV requires method calls, which are more verbose but make semantics explicit and easier to standardize across teams.
Equality and ordering in scoreboards
systemverilog
// Java: equals/hashCode/compareTo contract on domain objects
class Txn implements Comparable<Txn> {
int addr;
int data;
public boolean equals(Object o) {
if (!(o instanceof Txn)) return false;
Txn rhs = (Txn)o;
return addr == rhs.addr && data == rhs.data;
}
public int hashCode() { return 31 * addr + data; }
public int compareTo(Txn rhs) { return Integer.compare(addr, rhs.addr); }
}
// SystemVerilog: named methods with explicit intent
class txn;
rand int addr;
rand int data;
function bit equals(txn rhs);
return (addr == rhs.addr) && (data == rhs.data);
endfunction
function int compare(txn rhs);
if (addr < rhs.addr) return -1;
if (addr > rhs.addr) return 1;
return 0;
endfunction
function int unsigned hash();
return (addr * 32'd31) ^ data;
endfunction
endclassWithout operator hooks, you intentionally define semantic methods and make callers choose the right one (identity compare, field equality, ordering, or hash).