Can child_handle cast to parent_handle using $cast(c_h,p_h), if parent_handle is already not pointing child object and pointing to parent_handle?

P => parent class
C => child class extended from P

code

P p_h = new();
C c_h ;
$cast(c_h,p_h); // Is this valid/legal ?

In reply to jkpatel:

yes it is invalid.

because child class will not consist of portion of parent class which leads to COMPILE TIME ERROR.

In reply to janakiram6196:

The code is valid and results in a run-time casting error. I prefer the use of base class and derived or extended class instead of parent and child when we’re talking about inheritance. P is a base class and C is the derived class. It is always legal to downcast from a base variable (p_h) to a derived variable (c_h), but the cast only succeeds if the base class variable contains a handle to a derived object, or one of its derivatives.

You might want to look at my course on SystemVerilog OOP, especially the second section on inheritance.

Thanks a lot Dave

Another follow up doubt,

B // Base class
E // Extended class from B
EE // Extended class from E

E e_h ;
B b_h ;
EE ee_h ;

case #1
ee_h = new(); // instance created
b_h = ee_h ; // legal
$cast(e_h,b_h); // Is this also Valid ? Any runtime error ?

case #2
e_h = new(); // instance created
b_h = e_h ; // legal
$cast(ee_h,b_h); // Is this also Valid ? Any runtime error ?

If extended class handle pointing to base_class handle which is already pointing to same extended class handle, it will work but what if base class handle is pointing to one level up(case#2) or one level down(case#1).

Please clarify.

In reply to jkpatel:
This is all explained in my course SystemVerilog OOP. You should understand the difference between class variables and class handles, and the class types associated with each. A class variable can only hold a class handle whose type is the same or more derived than the type of the variable. A class variable type canny be more derived than the class handle type it holds.