Use struct to Handle Heterogeneous Data Elements in C++

Use struct to Handle Heterogeneous Data Elements in C++

Have you ever come across an application where you’re required to handle more than one set of heterogeneous data elements? Operations may include initialising, reading from, writing to, and passing data to different parts of the application.

For exmple, suppose you’ve got an application that deals with employee data?things like ID, name, salary, etc. In these cases, you’d use a “binding device” like a struct, instead of separate variables:

struct Employee{  char		szName[50];  long		nDeptCode;  char		chGrade;  double	dSal;};

There are a number of advantages to using this method:

  1. One-shot initialisation (irrespective of data types inside the structure):
        struct Employee obj1;  memset ((void *)struct Employee obj1,            ' ',            sizeof(struct Employee obj1));

    All the bytes of all the elements get reset.

  2. One-shot copying of objects:
      struct Employee objAllan;  struct Employee objBen;    objAllan.szName = Allan Davidson;  objAllan.nDeptCode = 2;  objAllan.chGrade = 'A';  objAllan.dSal = 10000;  objBen = objAllan;

    objBen gets identical values in its elements as objAllan.

  3. Flexibility in passing parameters.

The application typically has a set of functions which use some or all of the data elements for their processing. You can always pass the necessary variable and write the implementation as follows:

  void func1(char pchGrade)  {    // ...  }  int func2(char *pszName, double pdSal)  {    // ...  }

However, using a structure, the implementation becomes more precise and readable. The entire data set is communicated using a single identifier. This approach can also give a uniform look to the functions:

  • Passing the argument:
      struct Employee obj1;  // ...  func(obj1);
  • Using the argument:
      void func1(struct Employee st)  {    st.chGrade = 'A'    // ...  }  }
  • Passing the argument:
      struct Employee * pobj1;  // ...  pobj1 = (struct Employee *)malloc(sizeof(struct Employee));  func(pobj1);  // ...  free(pobj1);
  • Using the argument:
      void func2(struct Employee * pst)  {    pst->dSal = 10000.00;    // ... ... ...  }

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist