Difficulty: Easy · Puzzle 1 of 6 · Topic: Virtual Method Puzzles
A framework stores derived objects in base handles. Predict output and explain why only one method dispatches to derived.
class checker_base;
function string mode();
return "BASE";
endfunction
virtual function string detail();
return "base-detail";
endfunction
endclass
class checker_ext extends checker_base;
function string mode();
return "EXT";
endfunction
function string detail();
return "ext-detail";
endfunction
endclass
initial begin
checker_base c;
checker_ext e;
e = new();
c = e;
$display("mode=%s detail=%s", c.mode(), c.detail());
endDispatch behavior is determined by virtual-ness in the base declaration.
1) `mode()` is non-virtual in base, so call binds statically to `checker_base::mode`.
2) `detail()` is virtual in base, so call dispatches dynamically to `checker_ext::detail`.
3) Output becomes `mode=BASE detail=ext-detail`.Answer: Output is `mode=BASE detail=ext-detail`; non-virtual methods bind to static handle type while virtual methods use runtime object type.
Checked by running the code in Verilator 5; the printed output supports the answer above. The shown code run in Verilator: only the virtual method dispatches to the derived class.
Declaring a method in the derived class does not create polymorphism unless the base declaration is virtual; the call site's handle type decides for `mode()`.
If `mode` is made virtual only in derived, does behavior change through `checker_base` handle? Model answer: no. `c.mode()` still prints `BASE` because the base declaration is non-virtual and the call binds to the handle type; only a call through a `checker_ext` handle (`e.mode()`) sees `EXT`, and it starts a new virtual chain for further subclasses. (Verified in Verilator.)
The output is mode equals BASE and detail equals ext-detail. A non-virtual method binds to the type of the handle, so mode runs the base version. A virtual method dispatches on the type of the actual object, so detail runs the extended version. The trap is assuming every method behaves polymorphically, so I would check which methods are declared virtual in the base.