C++ structures
Consider we want to make a program to store the database of the students of a school. For each student we have data like name class, section age and roll number. If we were to use the procedural approach this program would be very big and confusing hence we make use of structures.
A structure is a user-defined data type which is created using primitive and derived data types. It is basically a group of data members enclosed by parenthesis.
spot the mistake in the given code
In a structure all members are public by default, which means we can access these members from outside the structure using a variable of the "structName" data type.
Accessing the members is done by declaring a variable whose data-type is the name of the structure.
Consider the following code.
A structure definition should always end with a semicolon.
As we have already learned in the chapter data types a structure is a collection of data members which define a particular thing like a car or student or anything in the real world.
Now based on Our knowledge of structures lets create an application to store data-base of patients in a hospital. The application should accept patient details like patient ID, Name and disease.
We also display this data.
We can also use typedef to give a different name to our structure and use it throughout the program.
There are 2 methods in which we can do this:
- We can write a typedef statement after the structure as shown below.
In the above example "sq" and "square" refer to the same structure.
- Another way to perform this is to write typedef before struct i.e. we include typedef before defining the structure and after defining the structure before the semi-colon we write the desired alternate name for the structure.
Syntax