Online Structures in C++ Programming basic Tutorial with Example data Structure Topic Source code
STRUCTURESStructures are aggregate data types consisting of other elementary data types. As an example we can declare a structure named complex that contains two data members: an integer variable real and another integer variable imaginary. Unlike arrays (all the members of which have to be of the same type), a structure may consist of elements belonging to different data types. For example a structure named book may be declared which has three members: an integer variable id, a floating type variable price and a character array title.
Try to think of many real life objects that you can represent by structures.
How to Use Structures?Structures can be declared by using the keyword struct. For example the structures complex can be declared as:
struct book // keyword struct tells that book is a structure
int id ;
float price ;
char title ;
}; //note the semicolon (;) at the end of
book sowkoski ; //declares an instance of type book and names it sowkoski
book Csbooks; // an array of type book is declared
Note the similarity between declaring an instance of a built in data type ( int num; int a;) and that of a user defined data type( book sowkoski; book Csbooks; )Alternatively an instance of a structure may also be declared along with the structure definition but usually this is not the preferred method. An example follows that declares two instances of a structure complex with its definition. The structure name may be omitted in such a case but this disallows creation of any more instances in the program.
struct complex // keyword struct tells that complex is a structure
int imaginary ;
} c1, c2 ; //declares two instances of the structure complex
How to Access the Members of a Structure?
The dot operator (.) is used to access the members of a structure. Following examples elaborate the use of the dot operator:
cout<<"Sowkoski's ID is "<<sowkoski.id;
cout<<"\n Enter title for first CS book: ";