0% found this document useful (0 votes)
8 views9 pages

Structures in C++

Structures in C++ are user-defined data types that allow the grouping of items of different data types, unlike arrays which only store similar data types. They can contain data members and member functions, and can be initialized and accessed using specific syntax. The document also highlights the differences between structures and classes in C++, particularly in terms of access control and declaration syntax.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Structures in C++

Structures in C++ are user-defined data types that allow the grouping of items of different data types, unlike arrays which only store similar data types. They can contain data members and member functions, and can be initialized and accessed using specific syntax. The document also highlights the differences between structures and classes in C++, particularly in terms of access control and declaration syntax.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

STRUCTURES IN C++ in

We often come around situations where we need to store a group


of data whether of similar data types or non-similar data types.
We have seen Arrays in C++ which are used to store set of data
of similar data types at contiguous memory locations.
Unlike Arrays, Structures in C++ are user defined data types
which are used to store group of items of non-similar data types.
What is a structure?
A structure is a user-defined data type in C/C++. A structure
creates a data type that can be used to group items of possibly
different types into a single type. 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++

Data Member: These members are normal C++



variables. We can create a structure with variables of
different data types in C++.
 Member Functions: These members are normal C++
functions. Along with variables, we can also include
functions inside a structure declaration.
Example:
 C++
// Data Members
int roll;
int age;
int marks;

// Member Functions
void printDetails()
{
cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\n";
cout<<"Marks = "<<marks;
}

In the above structure, the data members are three integer


variables to store roll number, age and marks of any student and
the member function is printDetails() which is printing all of the
above details of any student.
How to declare structure variables?
A structure variable can either be declared with structure
declaration or as a separate declaration like basic types.

 C++
// A variable declaration with structure declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct Point
{
int x, y;
};

int main()
{
struct Point p1; // The variable p1 is declared like a normal
variable
}

Note: In C++, the struct keyword is optional before in declaration


of a variable. In C, it is mandatory.

How to initialize structure members?


Structure members cannot be initialized with declaration. For
example the following C program fails in compilation.
But is considered correct in C++11 and above.
 C++
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

The reason for above error is simple, when a datatype is declared,


no memory is allocated for it. Memory is allocated only when
variables are created.
Structure members can be initialized with declaration in
C++. For Example the following C++ program Executes
Successfully without throwing any Error.
 C++
// In C++ We can Initialize the Variables with Declaration in
Structure.

#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;

// Accessing members of point p1


// No value is Initialized then the default value is
considered. ie x=0 and y=1;
cout << "x = " << p1.x << ", y = " << p1.y<<endl;

// Initializing the value of y = 20;


p1.y = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
}
// This code is contributed by Samyak Jain

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 };
}

How to access structure elements?


Structure members are accessed using dot (.) operator.
 C++
#include <iostream>
using namespace std;

struct Point {
int x, y;
};

int main()
{
struct Point p1 = { 0, 1 };

// Accessing members of point p1


p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;

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];

// Access array members


arr[0].x = 10;
arr[0].y = 20;

cout << arr[0].x << " " << arr[0].y;


return 0;
}

Output
10 20

What is structure member alignment?

In C++, a structure is the same as a class except for a few


differences. The most important of them is security. A Structure is
not secure and cannot hide its implementation details from the
end user while a class is secure and can hide its programming
and designing details.

Member Functions in C++ Structures


In C++, structures can also have member functions.

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.

We can declare a member function by defining the function within the


structure definition.

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;
}
};

In this example, the Person structure includes a member


function, displayInfo() which displays the information about the person.
Let's look at an example.
#include <iostream>
using namespace std;

struct Person {
string first_name;
string last_name;
int age;
float salary;

// member function to display information about the person


void display_info() {
cout << "First Name: " << first_name << endl;
cout << "Last Name: " << last_name << endl;
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
}
};

int main() {
Person p1;

cout << "Enter first name: ";


cin >> p1.first_name;
cout << "Enter last name: ";
cin >> p1.last_name;
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

// display information using member function


cout << "\nDisplaying Information." << endl;
p1.display_info();

return 0;
}
Run Code

Output

Enter first name: Jane


Enter last name: Smith
Enter age: 27
Enter salary: 10000

Displaying Information.
First Name: Jane
Last Name: Smith
Age: 27
Salary: 10000

DIFFERENCE BETWEEN STRUCTURES & CLASS IN C++


30 Aug, 2024



In C++, a structure works the same way as a class, except for just
two small differences. The most important of them is hiding
implementation details. A structure will by default not hide its
implementation details from whoever uses it in code, while a class
by default hides all its implementation details and will therefore
by default prevent the programmer from accessing them. The
following table summarizes all of the fundamental differences.
S.
No. Class Structure

Members of a class are private by Members of a structure are public by


1 default. default.

2 It is declared using the class keyword. It is declared using the struct keyword.
S.
No. Class Structure

It is normally used for data It is normally used for the grouping of


3 abstraction and inheritance. different datatypes.

Syntax: Syntax:
class class_name { struct structure_name {
data_member; structure_member1;
member_function; structure_member2;
4 }; };

Some examples that elaborate on these differences:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy