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:
We define a
BASE-STRUCT
with aNUM
field.We then define a
CONTAINER-STRUCT
which includesBASE-STRUCT
as a nested structure, along with an additionalSTR
field. This is similar to embedding in other languages.In the
MAIN-PROCEDURE
, we initialize the structures and set values.We can access the
NUM
field of the base structure directly through the container structure, similar to how embedding works in other languages.We define two procedures,
DESCRIBE-BASE
andDESCRIBE-CONTAINER
, which are analogous to methods in object-oriented languages. These procedures fill theDESCRIBER
variable with a description string.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.