Heterogeneous Arrays in Data Sturcture


As we know the arrays are homogeneous by definition. So we have to put data of same type in an array. But if we want to store data of different type, then what will be the trick? In C like old languages, we can use unions to artificially coalesce the different types into one type. Then we can define an array on this new type. Here the kind of object that an array element actually contains is determined by a tag. Let us see one structure like this −

struct Vehicle{
   int id;
   union {
      Bus b;
      Bike c;
      Car d;
   }
};

Then the programmer would have to establish a convention on how the id tag will be used. Suppose, for example, when the id is 0, it means that the Vehicle which is represented is actually a Bus etc. The union allocates memory for the largest type among Bus, Bike and Car. This is wasteful for memory if there is a great disparity among the sizes of the objects.

In the object oriented languages, we can use the concept of inheritances. Suppose we have a class called Vehicle, and all other types like Bus, Bike and Car are the sub-class of it. So if we define an array for Vehicle, then that can also hold all of its sub-classes. This will help us to store multiple types of data in a single array.

Updated on: 10-Aug-2020

888 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements