top of page
Search
Writer's pictureHarshit Sharma

STRUCTURE IN C++

Structure is a grouping of several variables under one name .A structure is collection of data while a class is a collection of data and function.A structure is a class declared with keyword struct and by default all members are public in structure whereas all members are private by default in class.

Syntax:

struct<structure tag>

{

data members, declarations

member functions,declarations

};

Example:

Struct date

{

Short day;

Short month;

Short year;

};

We can also declare a structure variable of a structure outside the structure also

Struct tag{

Type variable name;

Type variable name;

}structure variables;

Refrencing Structure element

Once a structure is defined its members can be accessed through the use of the dot operator.

Syntax:

Structure name.element name

Birth_date.year=1740;

The first component of an expression involving the dot operator is the name of the specific structure variable (birth_date in this case)

Program to understand structure

#include<iostream.h>

#include<conio.h>

struct emp

{

int empno;

char name[6];

float basic;

}worker;

int main()

{

cout<<"Enter employee no";

cin>>worker.empno;

cout<<"Name";

cin>>worker.name;

cout<<"Basic pay";

cin>>worker.basic;

getch();

return 0;

}

Initializing Structure elements

The structure elements of a structure can be initialized either seperately using separate assignment statements or jointly using the notation similar to array initialization.

For example:

Strcut stutype

{

Short rollno;

Float marks;

Char grade;

}senior_student ;

Senior_student.rollno=01;

Senior_student.marks=50.00;

Senior_student.grade=’A’;

OR

Stutype senior_student =(01,50.00,’A’);

It can only be defined if we define this senior_student variable after the structure.

Strcut stutype

{

Short rollno;

Float marks;

Char grade;

};

Stutype senior_student;

Structure rules

1.Whenever we define a structure it should be defined with the word struct

2.The structure should also end with a ; after the } whenever the block of structure is completed.

3.We can access the members of structures by using(.) dot operator

4.Structure variables to access the data member can be defined inside the main function or can also be defined after the struct block.

5.We can include structure within structure as nested structures,or way can make array of structure or using functions ,array in structures also.

8 views0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page