Quantcast
Channel: Java Question Bank » Cpp Programs
Viewing all articles
Browse latest Browse all 22

Why union Is more Efficient

$
0
0

Structures  and unions are the most commonly used user defined data types

Every one is familiar with the syntax and use of structures and unions

Here we will discuss

WHY UNION IS MORE EFFICIENT ALTERNATIVE OF STRUCTURES PARTICULARLY IN SITUATIONS WHERE IT IS NOT REQUIRED TO ACCESS THE DIFFERENT MEMBER ELEMENTS SIMULTANEOUSLY.

Let us  illustrate with some simple examples

1
2
3
4
5
6
7
Struct</p>
<p>{</p>
<p>Int marks;</p>
<p>Char grade</p>
<p>Float percent;</p>
<p>};</p>
<p>

In the above declaration the memory consumed for the different datatypes is

Int 2,char 1, float 4 total =7  i.e the size of the structure type is equal to the sum of the sizes of individual member types.

The union will result total size consumed is  4, ie the size of the union is equal  to the size of its largest member element , in the above declaration largrst memory size is float .

Thus in case of unions the same memory space is used for representing the different member element .as a result union members can be manipulated exclusive of each other .

ARRAY OF OBJECTS :

We know that array can be any data type including struct ,similarly we can also have arrays of variables

That are of the type class such variables are called  array of object .

Consider the following class definition

1
2
3
4
5
6
7
8
9
10
</p>
<p>Class  employee</p>
<p>{</p>
<p>Char name[30];</p>
<p>Float age;</p>
<p>Public;</p>
<p>Void getdata(void);</p>
<p>Void putdata(void);</p>
<p>};</p>
<p>

The identifier employee is a user-defined data type and can be used to create objects that relate to different categories of the employee

Employee manager[3];                                  //array of manager

Employee foreman[15];                                                // array of foreman

Employee worker[75];                                // array of worker

 

The array manager contains three objects namely manager[0], manager[1] and manager[2]

Similarly the other two.

Since an array of object behaves like any other array, we use the usual array- accessing methods to access individual elements, and then the dot member operator to access the member functions.

Example manager[i].putdata();

Display the data of the ith element of the array manager. That is the statement requests the object manager[i] to invoke the member function putdata().

(15)

18 total views, 5 views today


Viewing all articles
Browse latest Browse all 22

Trending Articles