Struct Embedding in COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. STRUCT-EMBEDDING.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 BASE-STRUCT.
           05 NUM PIC 9(5).
       01 CONTAINER-STRUCT.
           05 BASE-STRUCT.
           05 STR PIC X(20).
       01 DESCRIBER PIC X(30).

       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           INITIALIZE BASE-STRUCT
           INITIALIZE CONTAINER-STRUCT
           MOVE 1 TO NUM OF BASE-STRUCT OF CONTAINER-STRUCT
           MOVE "some name" TO STR OF CONTAINER-STRUCT

           DISPLAY "co={num: " NUM OF BASE-STRUCT OF CONTAINER-STRUCT
                    ", str: " STR OF CONTAINER-STRUCT "}"

           DISPLAY "also num: " NUM OF BASE-STRUCT OF CONTAINER-STRUCT

           PERFORM DESCRIBE-BASE
           DISPLAY "describe: " DESCRIBER

           PERFORM DESCRIBE-CONTAINER
           DISPLAY "describer: " DESCRIBER

           STOP RUN.

       DESCRIBE-BASE.
           STRING "base with num=" NUM OF BASE-STRUCT
               DELIMITED BY SIZE
               INTO DESCRIBER.

       DESCRIBE-CONTAINER.
           MOVE FUNCTION CONCATENATE(
               "base with num=",
               FUNCTION TRIM(NUM OF BASE-STRUCT OF CONTAINER-STRUCT)
           ) TO DESCRIBER.

COBOL doesn’t have a direct equivalent to struct embedding as found in some other languages. However, we can simulate a similar concept using nested structures.

In this COBOL program:

  1. We define a BASE-STRUCT with a NUM field.

  2. We then define a CONTAINER-STRUCT which includes BASE-STRUCT as a nested structure, along with an additional STR field. This is similar to embedding in other languages.

  3. In the MAIN-PROCEDURE, we initialize the structures and set values.

  4. We can access the NUM field of the base structure directly through the container structure, similar to how embedding works in other languages.

  5. We define two procedures, DESCRIBE-BASE and DESCRIBE-CONTAINER, which are analogous to methods in object-oriented languages. These procedures fill the DESCRIBER variable with a description string.

  6. We call these procedures and display their results, simulating method calls on the structures.

While COBOL doesn’t have interfaces or method embedding like some object-oriented languages, this example demonstrates how to achieve similar functionality using COBOL’s structured programming features.

When you run this program, it will output:

co={num: 00001, str: some name           }
also num: 00001
describe: base with num=00001
describer: base with num=00001

This output mimics the behavior of the original example, showing how we can access the embedded structure’s fields and “methods” through the container structure.