Extending parameterized classes

Hi All,

In the following example,

class Trans #(int awidth=8, dwidth=8);
    string name;
    function new(string name = "");
        this.name = name;
    endfunction
    virtual function void display();
        $display("name = %s, awidth=%0d, dwidth=%0d",this.name,awidth,dwidth);
    endfunction
endclass

class Trans16#(int awidth=16, dwidth=16) extends Trans;
    function new(string name = "");
        super.new(name);
    endfunction
endclass

module tb_top();
Trans t1,t2;
Trans16 t16_1,t16_2;
initial begin
    t1 = new("t1");
    t16_1 = new("t16_1");
    t1.display();
    t16_1.display();

end
endmodule

Here t16_1.display() function gives 8 not 16. Why does it not give 16?
I think Im missing some fundamental concepts here. Appreciate any/all comments.

Your problem is you did not pass your parameter values down to the base class Trans. Try writing your classes like:

class Trans #(int awidth, dwidth); // removing defaults forces you to provide overrides
    string name;
    function new(string name = "");
        this.name = name;
    endfunction
    virtual function void display();
        $display("name = %s, awidth=%0d, dwidth=%0d",this.name,awidth,dwidth);
    endfunction
endclass

class Trans16#(int awidth=16, dwidth=16) extends Trans#(awidth,dwidth);
    function new(string name = "");
        super.new(name);
    endfunction
endclass

Thanks @dave_59 . That solved the problem.

Also is there any way/method we can use the handle of the base_class (8,8) point to a derived class with a different parameter like (16,16)?

It all depends on what you are trying to accomplish. There is nothing saying you have to link the derived class parameters to the to the base class parameters. But if the base class needs the derived parameter values, then it becomes a different incompatible class type. What people sometimes do in that case is create another lower level base class without parameterizations.

 virtual class base_trans; // an abstract class that never gets constructed. 
    pure virtual function void display;
 endclass
 class Trans #(int awidth, dwidth) extends base_trans;
 ...
 endclass
class DerivedTrans#(int awidth, dwidth) extends Trans#(awidth,dwidth);
...
endclass
base_trans list[$];
DerivedTrans#(16,16) trans16   = new("trans16");
DerivedTrans#(32,32) trans32   = new("trans32");
list.push_back(trans16);
list.push_back(trans32);
foreach(list[i]) list.display();

Thanks a lot @dave_59 That did the trick.