In C++, a structure is a user-defined data type that allows you to group together different variables of various types (int, string, bool, etc.) under a single name. Structures provide a way to organize related data elements into a cohesive unit.
Create a Structure:
A structure is defined using the `struct` keyword, followed by the name of the structure. Inside the structure, you can declare member variables of different types, similar to declaring variables in other contexts.
struct MyStruct
{
// Member variables
int intValue;
float floatValue;
char charValue;
};
Member Access:
You can access the member variables of a structure using the dot (`.`) operator. For example:
struct MyStruct
{
int intValue;
};
int main()
{
MyStruct myStruct;
myStruct.intValue = 30; // Accessing member variable
cout << "Value: " << intValue << endl;
return 0;
}
Functions and Methods in Structure:
Structures can contain member functions in addition to member variables. These functions are referred to as methods and operate on the data within the structure.
struct MyStruct
{
int intValue;
// Member function
void printValue()
{
cout << "Value: " << intValue << endl;
}
};
int main()
{
MyStruct myStruct;
myStruct.intValue = 40; // Accessing public member variable
myStruct.printValue(); // Calling public member function
return 0;
}