Say I have these classes:
class base;
int x;
endclass
class derive1 extends base;
int y;
endclass
class derive2 extends derive1;
int z;
endclass
Is it possible to cast a base class instance straight to a derive2 class instance? like this:
program prg;
base b1;
derive2 d2;
$cast(d2,b1);
endprogram
Certainly. But it will only work if the object is being cast is indeed a derive2 class.
Here is a complete self-contained example, with code tags. Please show your code this way so it is easy for others to give it a try.
module prg;
class base;
int x;
endclass
class derive1 extends base;
int y;
endclass
class derive2 extends derive1;
int z;
endclass
base b1,b;
derive2 d2,d;
initial begin
d = new();
b1 = d; // no $cast needed
$cast(d2,b1); // $cast needed, and will succeed
b1 = new;
$cast(d2,b1); // $cast needed, and will fail
end
endmodule
In reply to dave_59:
why $cast will fail when child handler d2 pointing parent b1
In reply to ramana4210:
I would avoid using the terms parent and child when discussing inheritance. A derived class object includes (inherits) all properties of the base class type - it is not a separate object.
The reason the last $cast fails is that b1 holds a handle to a base type class object. It has no proprieties that the target class variable needs. i.e. d2.z does not exist.