oop - Upcasting accesses -
let's have planet:
type planet tagged null record; type planet_ref access planet'class; now subclass it:
type habitable_planet new planet null record; type habitable_planet_ref access habitable_planet'class; now define variables:
p: planet_ref := make_planet; hp: habitable_planet_ref := make_habitable_planet; i naively expect assigning p := hp work, because habitable_planet subclass of planet. of course won't work because every type defined type distinct , doesn't interoperate other type.
so i'd expect have declare habitable_planet_ref subtype of planet_ref make work. syntax doesn't seem allow this.
how make work?
(yes, know can use explicit view conversion cast habitable_planet_ref planet_ref, that's ugly , i'd avoid it.)
ada recognizes types name, indeed need view conversion here. if using ada 2005, can use anonymous access types instead. instance:
hp: access habitable_planet'class := make_habitable_planet; p: access planet'class := hp; -- valid anonymous access types one drawbacks of using anonymous access types code more verbose (although in general not use them local variables, parameters subprograms or fields in (tagged) record. can't used unchecked_deallocation. in fact, use them because of that: when have field in record of anonymous access type, know record not "own" accessed data, , therefore should not free (in fact, have write convoluted code free them). , of course per request result type matching more relax, nice too.
Comments
Post a Comment