Structure in C++

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 datatypes. 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 a variables

Example:

struct notebook

{

int notebookid;

Char name[20];   

Float actualprice;

}

Void main()

struct notebook b1; // here in C++, struct keyword is optional 

}

In 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], actualprice.

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 dot (.) operator.

For e.g.

b1.notebookid = 201;


Difference between C++ structure and C structure

C StructuresC++ Structures
Access modifiers are absent in C structures.C++ structures support access modifiers.
Does not permit Data hiding.Since C++ contain oops concept, it permits Data hiding concepts.
For empty structure, sizeof operator create 0For empty structure, sizeof operator create 1 in C++
It does not support direct initialization of structure data membersPermits direct initialization of structure data members
It does not permit member functions inside the structure along with data members.It permits data members inside structure
Static members are not allowedStatic members are allowed

Coding Tag

Coding Tag always happy to serve you in Information Technology (IT). Learn HTML, CSS, Javascript, PHP, Android, Digital Marketing, Latest IT News and many more.

Leave a Reply

avatar
  Subscribe  
Notify of