Some SystemVerilog constructor insights
Can you predict the printed messages of the two statements within the initial block? 🧐
//----------------------------------//
class C;
integer c1 = 1;
integer c2 = 1;
integer c3 = 1;
function new(integer a);
c2 = 2;
c3 = a;
endfunction
endclass
//---------------------------------//
class D extends C;
integer d1 = 4;
integer d2 = c2;
integer d3 = 6;
function new;
super.new(d3);
endfunction
endclass
//---------------------------------//
module test;
initial begin
C c0 = new(5);
D d0 = new;
$display("c0 variables c1:%0d, c2:%0d, c3:%0d", c0.c1, c0.c2, c0.c3);
$display("d0 variables c1:%0d, c2:%0d, c3:%0d, d1:%0d, d2:%0d, d3:%0d",
d0.c1, d0.c2, d0.c3, d0.d1, d0.d2, d0.d3);
end
endmodule
Before unveiling the answer, let's explore some key points mentioned in SystemVerilog LRM regarding Constructors:
class Packet
integer command;
function new();
command = IDLE;
endfunction
endclass
Packet p = new; // new is called a class constructor
Recommended by LinkedIn
Applying those points to our example
For c0 object:
==============
c1 | 1 | 1 |
----->>-----
c2 | 1 | 2 |
----->>-----
c3 | 1 | 5 |
So the first printed message will be : c0 variables c1:1, c2:2, c3:5
For d0 object (Derived class):
=============================
c1 | 1 | 1 |
----->>-----
c2 | 1 | 2 |
----->>-----
c3 | 1 | x |
----->>-----
d1 | x | 4 |
----->>-----
d2 | x | 2 |
----->>-----
d3 | x | 6 |
Note: c3 has an undefined value since the constructor call from D passes in the value of d3, which is
undefined when the super.new(d3) call is made
So the second printed message will be : d0 variables c1:1, c2:2, c3:x, d1:4, d2:2, d3:6
Would you be willing to attempt the same approach with the following example to see if you've grasped it? 🤔 Let me know how it goes!
class C
int c1 = 1;
int c2 = 2;
int c3 = 3;
function new(int a);
c2 = 2;
c3 = a;
endfunction
endclass
//---------------------------------//
class D extends C;
int d1 = 4;
int d2 = c2;
int d3 = 6;
function new;
super.new(d3);
endfunction
endclass
//---------------------------------//
module test;
initial begin
C c0 = new(5);
D d0 = new;
$display("c0 variables c1:%0d, c2:%0d, c3:%0d", c0.c1, c0.c2, c0.c3);
$display("d0 variables c1:%0d, c2:%0d, c3:%0d, d1:%0d, d2:%0d, d3:%0d",
d0.c1, d0.c2, d0.c3, d0.d1, d0.d2, d0.d3);
end
endmodule;