OOP: Interface methods/properties with different return types

lefish
2022-11-21
2022-11-25
  • lefish - 2022-11-21

    Hi there,

    can I somehow achieve to let the function blocks which implement an interface decide which data type is actually returned?

    So let FB_A return Type_A and FB_B return Type_B when calling an interface I_AB method.

    Basically I need to change the return type of an overloaded method/property according to the method/property called.

    I can explain more detail of what I am trying to achieve, but I would like to keep it abstract for the opening of the thread (lenghtiness of thread where it might not be needed)

    I tried to form a Union of Type_A and Type_B, return always the union and decide on runtime which element to use, but this is very error prone during development as it exposes Type_A to implementations of FB_B function block.

    Can you point me into the right direction please?

    Thanks in advance!

    Best regards
    LeFish

     

    Last edit: lefish 2022-11-21
  • sgronchi - 2022-11-22

    In general you cannot return a different data type except with a union.

    If you want stronger typechecking, you could return a pointer to the data (in pointer to byte) and a reference to a "decoding interface" that inherits from a base one with no .Decode method, and then you dispatch via __QUERYINTERFACE.

     
  • fajean - 2022-11-22

    Are you trying to achieve the equivalent of generics (i.e. have a "container" function block that contains elements of an arbitrary type, but all elements of the same type for a given instance of the container) or mixed types (i.e. elements of different types within the same container)?

     
  • lefish - 2022-11-25

    Thanks for your replies.

    @fajean: Basically this is what I am trying to achieve. I need to pack FBs with commonly named properties (returning different kinds of structs) into one array to loop over all FBs. It would have been great for this purpose if a propertyX returned a structA when queried for an instance of typeA, but a propertyX returned a structB when queried for instance of typeB...

    I solved this now by dropping the Interface-approach at all. Instead I implemented "Interface"-Methods and Properties in a FB_Handler (which I needed anyways) to interact with the underlying instances of FB_A and FB_B.
    Typechecking is also to be implemented in this "Interface".

     

Log in to post a comment.