Structures in C++
Structures in C++
Last Updated
How to create a structure?
The ‘struct’ keyword is used to create a structure. The general
syntax to create a structure is as shown below:
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
Structures in C++ can contain two types of members:
Structures in C++
// Member Functions
void printDetails()
{
cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\n";
cout<<"Marks = "<<marks;
}
C++
// A variable declaration with structure declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'
int main()
{
struct Point p1; // The variable p1 is declared like a normal
variable
}
#include <iostream>
using namespace std;
struct Point {
int x = 0; // It is Considered as Default Arguments and no
Error is Raised
int y = 1;
};
int main()
{
struct Point p1;
x=0, y=1
x=0, y=20
Structure members can be initialized using curly braces ‘{}’. For
example, following is a valid initialization.
C++
struct Point {
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = { 0, 1 };
}
struct Point {
int x, y;
};
int main()
{
struct Point p1 = { 0, 1 };
return 0;
}
Output
x = 20, y = 1
What is an array of structures?
Like other primitive data types, we can create an array of
structures.
C++
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
Output
10 20
These member functions are similar to regular functions but are defined
within the scope of a structure. They can access and manipulate the data
members of the structure directly.
struct Person {
string first_name;
string last_name;
int age;
float salary;
// member function to display information about the person
void displayInfo() {
cout << "First Name: " << first_name << endl;
cout << "Last Name: " << last_name << endl;
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
}
};
struct Person {
string first_name;
string last_name;
int age;
float salary;
int main() {
Person p1;
return 0;
}
Run Code
Output
Displaying Information.
First Name: Jane
Last Name: Smith
Age: 27
Salary: 10000
2 It is declared using the class keyword. It is declared using the struct keyword.
S.
No. Class Structure
Syntax: Syntax:
class class_name { struct structure_name {
data_member; structure_member1;
member_function; structure_member2;
4 }; };