IEEE Std 1800-2012 § 8.16 "Casting" states:
It is always legal to assign an expression of subclass type to a variable of a class type higher in the inheritance tree (a superclass or ancestor of the expression type). It shall be illegal to directly assign a variable of a superclass type to a variable of one of its subclass types. However, $cast
may be used to assign a superclass handle to a variable of a subclass type provided the superclass handle refers to an object that is assignment compatible with the subclass variable.
The following cast failes because a superclass object not be read as an childclass.
m_base = new();
$cast(m_extend, m_base); // destination type != source object type
To cast correctly the object of the source handle must be compatible with the destination typetypes must be comparable:
m_extend = new();
m_base = m_extend;
$cast(m_extend, m_base); // destination type == source object type
Downcasting can work through levels of inheritance. The following example demonstrates a base class handle pointing a grandchild object being casted to the extend class (the grandchild object's parent class):
class ext_more extends extend;
int c;
endclass
initial begin
base m_base;
extend m_extend;
ext_more m_ext_more;
m_ext_more = new();
m_base = m_ext_more;
$cast(m_extend, m_base); // legal, casting a subclass object to a parent handle
$display(m_extend.a);
end
Here are some working example: http://www.edaplayground.com/s/6/587