21 Jan C++ Structures
Structures in C++ allow you to store data of different types. If you want to store variables of different types, such as int, float, char, etc. For example, storing the details of employees, with the following members:
- name: string type
- age: int type
- zone: string type
- salary: float type
Now, you would be wondering about the difference between structure and arrays. Well, Arrays store data of similar types, for example, an array of ints, whereas Structure stores data of different types.
Define a Structure
Let us understand the above concept with an example to define a structure in C++. To define a structure, use the struct keyword:
1 2 3 4 5 6 7 8 9 |
struct emp { char name[15]; int age; char zone[10]; float salary; }; |
Above,
- The name of the structure is emp,
- The structure members or fields are name, age, zone, and salary.
Declare a Structure
We defined the structure above. Let us now see how to declare. Following is an example to declare a structure while defining it:
Declare a structure while defining it
1 2 3 4 5 6 7 8 9 |
struct emp { char name[15]; int age; char zone[10]; float salary; }; e1, e2, e3; |
The e1, e2, and e3 above are variables. We can use them to access the values.
Declare a structure with struct
We can also declare the variables e1, e2, e3 using the struct keyword. First, define it:
1 2 3 4 5 6 7 8 9 |
struct emp { char name[15]; int age; char zone[10]; float salary; }; |
Declare e1, e2, and e3 of type emp:
1 2 3 |
struct emp e1, e2; |
Access Structure Members
To access a structure member in C++, use a period i.e., the member access operator. Following is the syntax:
1 2 3 |
structure_variable.structure_member |
For example, access the structure members for variable e1 i.e., the 1st employee:
1 2 3 4 5 6 |
e1.name e1.age e1.zone e1.salary |
Let us see an example of accessing structure members in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <string.h> using namespace std; // Declaring a structure "Emp" struct Emp { string name; int age; string zone; int salary; }; int main( ) { // Declare e1, e2, e3 of type Emp struct Emp e1; struct Emp e2; struct Emp e3; // Set the Employee1 information e1.name = "Jacob"; e1.age = 27; e1.zone = "East"; e1.salary = 25000; // Display Employee1 data cout<<"Employee1 name = "<<e1.name; cout<<"\nEmployee1 age = "<<e1.age; cout<<"\nEmployee1 zone = "<<e1.zone; cout<<"\nEmployee1 salary = "<<e1.salary; return 0; } |
Output
1 2 3 4 5 6 |
Employee1 name = Jacob Employee1 age = 27 Employee1 zone = East Employee1 salary = 25000 |
No Comments