In this video, you'll learn about structures in C++ programming, including what they are, how to define them, and how to use them in your code. Structure is a name given to a collection of variables of different data types. It is similar to a class in that both contain a collection of data of different types.
For example:
You want to store some information of a student : his/her name, rollno and grade. You can easily create different variables name, rollno and grade to store these information separately. However, in the future, you may want to save information for many people. Now you'd have to create different variables for each piece of information for each person: name name1, rollno1, grade1, name2, rollno2, grade2.
You can easily imagine how large and jumbled the code would be. It will also be a difficult task because there will be no relationship between the variables (information).
A better approach would be to group all related information under the name Student and use it for Student. The code is now much cleaner, readable, and efficient.
A structure is the collection of all related information under the single name (Student).
--------------------How to declare a structure in C++ programming?----------------
struct Student
{
string name;
int rollno;
char grade;
}
The struct keyword specifies a structure type, which is then followed by an identifier (name of the structure).
Then, inside the curly braces, you can declare one or more members of that structure (declare variables inside curly braces).
A person structure is defined here, with three members: name, rollno, grade.
No memory is allotted when a structure is created.
The definition of the structure merely serves as a template for the creation of variables. It is comparable to a datatype. When an integer is defined as follows:
int x;
The int indicates that only integers can be stored in the variable x. Similar to this, a structure variable's definition only specifies what property it will have.
When you declare a structure person, as shown above. A structure variable can be defined as follows:
Student std1;
A structure variable std1 of type structure Student is defined here.
The compiler only allocates the necessary memory after a structure variable is defined.
----------------------------How to access members of a structure?-----------------------
The dot (.) operator is used to access the members of a structure variable.
Assume you want to access the rollno of a structure variable bill and assign it 10. You can complete this task by executing the following code:
std1.rollno = 10;
#c++structures #structuresinc++programming #structuresinc++ #structure #structures #c++ #c++programming #c++tutorialforbeginners #c++course #codingwithclicks #coding #with #clicks
コメント