Ad Code

Responsive Advertisement

C++ struct - Learn CPP

C++ struct - Learn CPP, The type (struct) is used in the C++ programming language to define a new type of data, and this type can contain a different set of values, and these values can be of any type, but in an orderly and easy to deal with, and it can be said that ( Struct is a user-defined data type that allows the user to combine data elements of different data types under one name, and any new type that is defined by the programmer by the word (struct) is called (Structure), and any copy created of the new type is called (Object ).


C++ struct - Learn CPP


How to define a new struct in C++ programming language


The new type (struct) is defined in C++ as follows:



struct struct_name {

member_definition;


member_definition;

..

} object_names;


whereas:


  • (struct_name): The name that the programmer will give to the new type being created.
  • (member_definition): Here the programmer selects the name and type of any element he wants to make the new type own.
  • (object_names): If the programmer wants to create an instance of the new type directly when it is defined, it puts a name here and it will be considered a new object of it.


It is also possible to define the type (struct ) anywhere the programmer wants, as it can be defined in a special file or outside or inside the main function (() struct) in the C++ programming language:



struct Employee

{

char name[50];

int age;

float salary;

};


How to access elements inside a struct object in C++


To access the values of variables in the type (struct) in the C++ programming language, the programmer uses the operator (.), i.e. the regular dot, which is called (Member Operator) because it allows the programmer to access any (Member) element in the object that has been defined. Here is an example:



struct Employee

{

int age;

float salary;

};

int main() {

struct Employee e1 = {32, 4200};

//accessing the values in the variable

cout<< "Age : " << e1.age << endl;

cout<< "Salary : " << e1.salary << endl;

}