VLSI DV Interview Puzzles · All levels
Non-Virtual vs Virtual Through Base Handle
A framework stores derived objects in base handles. Predict output and explain why only one method dispatches to derived.
Puzzle
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.
Code
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;
c = new checker_ext();
$display("mode=%s detail=%s", c.mode(), c.detail());
endHint
Dispatch behavior is determined by virtual-ness in the base declaration.
Step-by-step solution
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
Answer: Output is `mode=BASE detail=ext-detail`; non-virtual methods bind to static handle type while virtual methods use runtime object type.
Why candidates get it wrong
Declaring method in derived does not create polymorphism unless base declaration is virtual.
Interviewer follow-up
If `mode` is made virtual only in derived, does behavior change through `checker_base` handle?