c++oopada

Ada interfacing C++: instance destroyed


I want to use a C++ library that implements the Factory Method design pattern.

Below you can see a minimal reproducibable example, including C++ sources and the Ada adapter.

And here I have the Ada files that imports C++ symbols, generated with a call to g++ -c -fdump-ada-spec -C ./Factory.h and doing some modifications to suite my taste:

And finaly an Ada main to test this silly example:

with Factory_h;
with Item_h;

procedure main is
  
  configured_item : constant access Item_h.Item'Class :=
    Factory_h.get_configured_item;
  
begin
  
  configured_item.do_something;

end main;

Do you know why if I comment out the Item primitives Delete_Item and Delete_And_Free_Item the call to do_something is never done and the item is destroyed?

If I uncomment them everything works.

Thanks in advance!


Solution

  • I'm far from expert on Ada-C++ interfacing, but my guess is that in the C++ code, do_something is the third entry in the virtual-function table for ConcreteItem. The dump-ada-spec operation adds Delete_Item and Delete_And_Free_Item to occupy the first two slots in the v-table on the Ada side, which makes do_something the third entry in the v-table, matching its position on the C++ side.

    When you comment out Delete_Item and Delete_And_Free_Item this makes do_something be the first entry in the v-table on the Ada side. So when Ada calls do_something, it actually calls the first v-table entry, which on the C++ side is some other function -- apparently one that performs Delete_Item.