Upcasting polymorphism seems not working

In the following piece of code, “k” is the handle to a base class object, and “c” is the handle to a derived class object of “k”. The assignment k=c lets the base handle hold the derived object handle.

Since the method “createObj()” is virtual, I would expect that k.creatObj() would call the method in the derived class. However, k.createObj() actually returns “object” type, meaning the method in the base class is called. This results the compiler compiling error for “c_h = k.createObj();”

That is unexpected. Could someone explain? Thanks.


virtual class Object;
endclass

class C extends Object;
endclass

virtual class ObjectProxy;
  pure virtual function Object createObj();
endclass : ObjectProxy

class ObjectWrapper #(type T = Object) extends ObjectProxy;
  virtual function T createObj();
    T obj;
    obj = new();
    return obj;
  endfunction
endclass


module v;
 
   ObjectProxy k;
   ObjectWrapper #(C) c = new;
   C c_h;
  
   initial begin

     k = c;
     c_h = k.createObj();

   end

endmodul

In reply to ningyangverificationacademy:

The compiler only knows that k.createObj() could return a class handle to an Object type or one of its derivatives. It has no knowledge of what the method in the derived class is actually going to do. So it has to assume an Object, and you need use $cast.