Sunday, August 30, 2009

Structures

Arrays can be used to handle several elements of the same type together. However, sometimes it would be useful to handle several data elements of different types as a unit. In C++ structures are used for this purposes.

Structures (like arrays) are called structured data types, i.e. they have a structure defined by the programmer. A structure is declared:

struct type_name
{
    data_type member_name1;
    ...
    data_type member_nameN;
};

This defines a new type called type_name which can be used as any other type in C++. Note the semicolon (;) at the end. It is a mandatory while declaring a structure.

The individual members in the structure act like any other variable with the type data_type. The members can be accessed using . (dot) operator:

struct Student
{
    string name;
    int student_number;
};
...
Student st; // Declare a new variable of type Student
...
st.name = "Harry Potter";
cin >> st.student_number;

The members of a structure can also be initialized with literals of the same type as the members:

Student harry=
{
    "Harry Potter", 12345
};

The members are initialized in the order they appeared at the declaration. A new value can be assigned to a structure with =, but comparison ( == and != ) is not possible.

The members can be of any type, including arrays:

struct Grade
{
    string name,
    int problem_points[4];
};
...
Grade grade1;
...
grade1.problem_points[2] = 5;

On the other hand, the elements of any array can be of any type, too, including structures:

Student students[200];
...
students[0].name = "Ron Weasley";
cin >> students[54].student_number;

A struct is an aggregate of elements of (nearly) arbitrary types. Structures allow the programmer to define a new data type and group related components together. When structure is passed as a parameter of a function, by default it is passed by value but it can be passed by reference as well.

Reference: fredosaurus, wikipedia, msdn


Previous post

Next post




No comments:

Post a Comment