Structures, Unions

How are Structures, Unions used in C++?

Explanation

Structure:


Structures in C++ is a collection of variables. Structures in C++ can be declared even without the keyword "struct". By default all the members of a structure are "public", even "private" members can also be declared in a function.

Syntax:


struct struct-type-name{
type name1: length;
type name2: length;
.
.
type nameN : length;
}variable_list;

Example :



#include <iostream.h>
struct Emp
{
int empno;
int empsal;
};
void main( )
{
Emp emp1= { 23, 12000};
cout << "Employee Number::" <<
emp1.empno << '\n';
cout << "Employee Salary:: "<< emp1.empsal;
}

Result :

Employee Number:: 23
Employee Salary:: 12000

In the above example, the structure "Emp" is used initialize the integers, that are referenced in the "main()" function.

Unions:


Unions in C++ is a user defined data type that uses the same memory as other objects from a list of objects. At an instance it contains only a single object.

Syntax:


union union-type-name{
type member-name;
type member-name;
}union-variables;

Example :


#include <iostream.h> union Emp
{
int num;
double sal;
}; int main()
{
Emp value;
value.num = 2;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
value.sal = 2000.0;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
return 0;
}

Result :

Employee number is::2
Salary is::2.122e-314
Employee number is::0
Salary is::2000

In the above example, only "value.num" is assigned, but still the "val.sal" gets a value automatically, since the memory locations are same.

C++ Tutorial


Ask Questions

Ask Question