The concept of structure in C++ comes when we need our own defined data types, it is a bit different from the classes, so don’t confuse it, it is the one where the concept of Object Oriented Programming starts and it is the main feature which makes a difference between C and C++, object oriented programming have just amazing factors. Now lets come to the point , for creating structures in C++ we write the keyword “struct” and then its name and use its attributes inside braces just like functions but with a semi colon at the end, we can define variables and functions inside a structure. lets have a look at the below example:
- // Simple Example of structures in C++
- //Student Records In C++ using structures
- #include<iostream>
- using namespace std;
- struct student
- { int roll_no;
- char name[20],city[20];
- int phone;
- };
- int main()
- { student std;
- cout<<“Enter roll number?”<<endl; cin>>std.roll_no;
- cout<<“Enter name of student?”<<endl; cin>>std.name;
- cout<<“Enter name of city of student?”<<endl; cin>>std.city;
- cout<<“Enter phone of student?”<<endl; cin>>std.phone;
- cout<<endl;
- cout<<“Roll no. : “<<std.roll_no<<endl;
- cout<<“Name: “<<std.name<<endl;
- cout<<“City: “<<std.city<<endl;
- cout<<“Phone: “<<std.phone<<endl;
- return 0;
- }
Now lets have an explanation of the above code, we defined a structure named “ student ” which contains the details of a student defined in different variables in it, now we can use it in our main() function with a “ . ” used after the self-defined variable “std “of datatype “student” . We can use the “ cin ” and ” cout ” operations with it. So simply structure makes our main() function much easier.