with Ada.Text_IO; use Ada.Text_IO;
--  A tagged object is passed by reference (RM 6.2(4)): a view conversion of it, or a call of
--  an inherited primitive, passes the object itself, so an operation that redispatches
--  (converts its formal to the class) reaches and writes the object's extension; an
--  assignment to an ancestor's view writes the ancestor's components only (RM 4.6(55))
procedure Main is
   package P is
      type Kind is (None, Root_Outer, Root_Inner, Child_Outer, Child_Inner);
      type Root is tagged record
         First, Second : Kind := None;
         N : Integer := 15;
      end record;
      procedure Inner (X : in out Root);
      procedure Outer (X : in out Root);
      procedure Twice (X : in out Root);
      type Child is new Root with record
         S : String (1 .. 3) := "abc";
      end record;
      overriding procedure Inner (X : in out Child);
   end P;
   package body P is
      procedure Inner (X : in out Root) is
      begin
         X.Second := Root_Inner;
      end Inner;
      procedure Outer (X : in out Root) is
      begin
         X.First := Root_Outer;
         Inner (Root'Class (X));
      end Outer;
      --  (passing the formal on to one that redispatches)
      procedure Twice (X : in out Root) is
      begin
         Outer (X);
         X.N := 30;
      end Twice;
      procedure Inner (X : in out Child) is
      begin
         X.Second := Child_Inner;
         X.S := "xyz";
      end Inner;
   end P;
   use P;
   V1, V2, V3, V4 : Child;
begin
   Outer (Root (V1));          --  a view conversion
   Outer (V2);                 --  the inherited primitive
   declare
      R : Root renames Root (V3);
   begin
      Twice (R);               --  a renamed view, passed on
   end;
   Root (V4) := (Root_Outer, Root_Inner, 7);
   Put_Line (Kind'Image (V1.First) & " " & Kind'Image (V1.Second) & " " & V1.S);
   Put_Line (Kind'Image (V2.First) & " " & Kind'Image (V2.Second) & " " & V2.S);
   Put_Line (Kind'Image (V3.Second) & " " & V3.S & Integer'Image (V3.N));
   Put_Line (Kind'Image (V4.First) & Integer'Image (V4.N) & " " & V4.S);
end Main;
