Structure & Union

Structure
In C++, structures and unions are the same as classes except that their members and inheritance are public by default.
A struct in the C++ programming language (and many derivatives) is a complex data type declaration that defines a physically grouped list of variables to be placed under one name in a block of memory, allowing the different variables to be accessed via a single pointer, or the struct declared name which returns the same address. The struct can contain many other complex and simple data type in an association, so is a natural organizing type for records like the mixed data types in lists of directory entries reading a hard drive (file length, name, extension, physical (cylinder, disk, head indexes) address, etc.), or other mixed record type (patient names, address, telephone... insurance codes, balance, etc.)
The C++ struct directly corresponds to the Assembly Language data type of the same use, and both reference a contiguous block of physical memory, usually delimited (sized) by word-length boundaries. Language implementations which could utilize half-word or byte boundaries (giving denser packing, using less memory) were considered advanced in the mid-eighties. Being a block of contiguous memory, each variable within is located a fixed offset from the index zero reference, the pointer.
A structure contains an ordered group of data objects. Unlike the elements of an array, the data objects within a structure can have varied data types. Each data object in a structure is a member or field.
Structure members are assigned to memory addresses in increasing order, with the first component starting at the beginning address of the structure name itself. To allow proper alignment of components, padding bytes may appear between any consecutive members in the structure layout.
#include < iostream.h >
struct Emp
{
int empno;
int empsal;
};
void main( )
{
Emp emp1= { 38, 10000};
cout << "Employee Number::" << emp1.empno << '\n';
cout << "Employee Salary:: "<< emp1.empsal;
}
Result:
Employee Number:: 38
Employee Salary:: 10000
Enumerated types
An enumerated type is a data type where every possible value is defined as a symbolic constant (called an enumerator). Enumerated types are declared via the enum keyword.Defining an enumerated type does not allocate any memory. When a variable of the enumerated type is declared (such as eColor in the example above), memory is allocated for that variable at that time.
Enum variables are the same size as an int variable. This is because each enumerator is automatically assigned an integer value based on it’s position in the enumeration list. By default, the first enumerator is assigned the integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator:
Enumerated types are incredibly useful for code documentation and readability purposes when you need to represent a specific number of states.
For example, functions often return integers to the caller to represent error codes when something went wrong inside the function. Typically, small negative numbers are used to represent different possible error codes.
Another use for enums is as array indices, because enumerator indices are more descriptive than integer indices.
Example: -
#include < iostream.h >
int main()
{
enum Fruits{orange, guava, apple};
Fruits myFruit;
int i;
cout << "Please enter the fruit of your choice(0 to 2)::";
cin >> i;
switch(i)
{
case orange:
cout << "Your fruit is orange";
break;
case guava:
cout << "Your fruit is guava";
break;
case apple:
cout << "Your fruit is apple";
break;
}
return 0;
}
Result: -
Please enter the fruit of your choice(0 to 2)::2
Your fruit is apple
Typedefs
Typedefs allow the programmer to create an alias for a data type, and use the aliased name instead of the actual type name. To declare a typedef, simply use the typedef keyword, followed by the type to alias, followed by the alias name:
typedef long name;
A typedef does not define new type, but is just another name for an existing type. A typedef can be used anywhere a regular type can be used.
Typedefs are used mainly for documentation and legibility purposes. Data type names such as char, int, long, double, and bool are good for describing what type of variable something is, but more often we want to know what purpose a variable serves.
Furthermore, typedefs allow you to change the underlying type of an object without having to change lots of code. For example, if you were using a short to hold a student’s ID number, but then decided you needed a long instead, you’d have to comb through lots of code and replace short with long. It would probably be difficult to figure out which shorts were being used to hold ID numbers and which were being used for other purposes.
However, with a typedef, all you have to do is change typedef short studentID to typedef long studentID and you’re done. Precaution is mandatory when changing the type of a typedef! The new type may have comparison or integer/floating point division issues that the old type did not.
Note that typedefs don’t mix particularly well with Hungarian Notation, and allow you to skirt some of the issues that using Hungarian Notation tries to prevent (such as being able to change a variable’s type without having to examine the code for areas where changing the type will be problematic).
Because typedefs do not define new types, they can be intermixed like normal data types.
One big advantage of typedefs is that they can be used to hide platform specific details. On some platforms, an integer is 2 bytes, and on others, it is 4. Thus, using int to store more than 2 bytes of information can be potentially dangerous when writing platform independent code.
Because char, short, int, and long give no indication of their size, it is fairly common for cross-platform programs to use typedefs to define aliases that include the type’s size in bits. For example, int8 would be an 8-bit integer, int16 a 16-bit integer, and int32 a 32-bit integer. Using typedef names in this manner helps prevent mistakes and makes it more clear about what kind of assumptions have been made about the size of the variable.
Example: -
#include < iostream >
typedef int AGE;
void main()
{
AGE i;
cout << "Enter your age::" << endl;
cin >> i;
cout << "Your age is::" << i << endl;
}
Result: -
Enter your age::
38
Your age is::38
Unions
A union is an object similar to a structure except that all of its members start at the same location in memory. A union variable can represent the value of only one of its members at a time.
A structure or union type definition contains the struct or union keyword followed by an optional identifier (the structure tag) and a brace-enclosed list of members.
The list of members provides a structure or union data type with a description of the values that can be stored in the structure or union. The definition of a member has the form of a standard variable declaration. The names of member variables must be distinct within a single structure or union, but the same member name may be used in another structure or union type that is defined within the same scope, and may even be the same as a variable, function, or type name.
Because incomplete types are not allowed as members, a structure or union type may not contain an instance of itself as a member, but is allowed to contain a pointer to an instance of itself. As a special case, the last element of a structure with more than one member may have an incomplete array type, which is called a flexible array member
A union member cannot be a class object that has a constructor, destructor, or overloaded copy assignment operator, nor can it be of reference type. A union member cannot be declared with the keyword static.
Example: -
// using_a_union.cpp
#include < stdio.h >
union NumericType
{
int iValue;
long lValue;
double dValue;
};
int main()
{
union NumericType Values = { 10 }; // iValue = 10
printf_s("%d\n", Values.iValue);
Values.dValue = 3.1416;
printf_s("%f\n", Values.dValue);
}
Output: -
10
3.141600
Anonymous unions
An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object.
The member names of an anonymous union must be distinct from other names within the scope in which the union is declared. You can use member names directly in the union scope without any additional member access syntax.
For example, in the following code fragment, you can access the data members i and cptr directly because they are in the scope containing the anonymous union. Because i and cptr are union members and have the same address, you should only use one of them at a time. The assignment to the member cptr will change the value of the member
An anonymous union cannot have protected or private members, and it cannot have member functions. A global or namespace anonymous union must be declared with the keyword static.
Structure & Union

Structure summary
* Structures are collections of related variables (or aggregates) under one name.
* Structures can contain variables of different data types.
* Keyword struct begins every structure definition. Between the braces of the structure definition are the structure member declarations.
* Members of the same structure must have unique names.
* A structure definition creates a new data type that can be used to declare variables.
* A structure can be initialized with an initializer list by following the variable in the declaration with an equal sign and a comma-separated list of initializers enclosed in braces. If there are fewer initializers in the list than members in the structure, the remaining members are initialized to zero (or a null pointer for pointer members).
* Entire structure variables may be assigned to structure variables of the same type.
* A structure variable may be initialized with a structure variable of the same type.
* Structure variables and individual structure members are passed to functions by value.
* To pass a structure by reference, pass the address of the structure variable or a reference to the structure variable. An array of structures is passed by reference. To pass an array by value, create a structure with the array as a member.
* Creating a new type name with typedef does not create a new type; it creates a name that is synonymous with a type defined previously.
Access Control and Constraints of Structures, Classes and Unions

Structures

Classes

Unions

class key is struct

class key is class

class key is union

Default access is public

Default access is private

Default access is public

No usage constraints

No usage constraints

Use only one member at a time


Free Web Hosting