Structure in C++
0 3295
With the structure, we can make a collection of both similar and dissimilar variables. while making structure actually we are creating data types which in C++ known as primitive data types.
Datatypes are generally used to make variables.
In structure, Instead of storing atomic value, we are able to store multiple values i.e records. If the structure is defined outside the main function then it is known as global definition whereas if the structure is defined inside the main function then it is known as it is locally defined.
Imp points of C++ Structure
- Collection of elements that are not similar
- Group variables
- Create datatypes
With the help of structure how to make variables:
Example:
struct notebook
{
int notebookid;
char name[20];
float actualprice;
}
void main()
struct notebook b1; // here in C++, struct keyword is optional
}
For example, we had made a structure name "notebook" and defined datatypes so the memory consumed in a defined part will be o bytes because, To consume memory, datatype needs to be initialized.
If we are using any data type, which is created with the help of structure, struct keyword is mandatory in C language but in C++ it is optional.
the b1 variable is 26 bytes memory block, which is locally defined structure variable, contains 3 sub-variables i.e. notebook, name[20], actual price.
struct notebook
{
int notebookid;
char name[20];
float actualprice;
}
void main()
struct notebook b1={100,"C++ by Monika",560.0}; // intialisation of structure variable
}
Structure variable can be accessed with the help of a dot (.) operator.
Example:
b1.notebookid = 201;
Difference between C++ structure and C structure
C Structures | C++ Structures |
Access modifiers are absent in C structures | C++ structures are supported access modifiers |
Does not permit data hiding | Since C++ contains oops concept, it permits data hiding concept |
For empty structure, size of operator create O | For empty structure, size of operator create 1 in C++ |
It does not support direct initialization of structure data members | Permit direct initialization of structure data members |
It does not permit member functions inside the structures along with data members. | It permits data members inside structures |
Static members are not allowed | Static members are allowed |
Share:
Comments
Waiting for your comments