C++ Structs

In C++, structs are user-defined types that are used to create structured objects. They allow us to collect variables of different data types in a single name. Structs are used for lightweight objects, such as rectangles, colors, Points, etc. In C++ , structs can contain data members and member functions .

Syntax

It has the following syntax:

Example

struct structure_name  

{  

     // member declarations.  

}

In the above declaration, a structure is declared by preceding the struct keyword followed by the identifier (structure name). Inside the curly {} braces, we can declare the member variables of different types.

In the above example, the cpptutorialech is a structure containing three variables: fullname, empid, and salary. When the structure is declared, no memory is allocated. When the variable of a structure is created, the memory is allocated.

Creating Structure Variable

Once the structure has been declared, a structure variable must be defined to allocate memory and store data. The data type for a structure variable is the structure name, which is followed by the variable name.

Syntax

It has the following syntax:

Example

struct Employee {

    string name;

    int age;

};

// Creating structure variable

Employee emp1;

Here, struct is the name of the structure, and Employee is the name of the variable.

Initializing Structure Members

In C++, it is not possible to initialize structure members within the structure definition at the moment of declaration. A C++ compiler error occurs in the example below:

Example

struct CppTutorial {

int q = 0; //compilation error

int j = 0; //compilation error

};

Curly braces{} can be used to initialize structure members when a variable is declared. The values are assigned according to the structure’s declared members’ order.

Example

struct Coordinate {

    int q, j;

};

int main() {

    // Initializing structure members

    Coordinate point1 = {15, 25};

}

In this example, two integer members, q and j, which represent coordinate values, are defined by the program as members of the Coordinate structure. The main function initializes a structure variable point1 with {15, 25}, assigning 15 to q and 25 to j.

Accessing Structure Members

Any members of a structure variable can be directly accessed by using the dot (.) operator to access structure members. The dot operator separates the name of the structure variable and the member name. The values stored in a structure can be retrieved or modified using this method.

C++ Struct Example

Let us take a C++ program to illustrate how to access structure members in C++.

Example

Example

#include <iostream>

using namespace std;

struct Student {

    string first_name;

    string last_name;

    int age;

    float grade;

};

int main() 

{

    // Defining a structure variable

    Student student1;

    // Assigning values to structure members

    student1.first_name = "Alice";

    student1.last_name = "Johnson";

    student1.age = 20;

    student1.grade = 90.5;

    // Displaying the structure members

    cout << "The First Name is: " << student1.first_name << endl;

    cout << "The Last Name is: " << student1.last_name << endl;

    cout << "Age is: " << student1.age << endl;

    cout << "The Grade is: " << student1.grade << endl;

    return 0;

}

Output:

Output

The First Name is: Alice

The Last Name is: Johnson

Age is: 20

The Grade is: 90.5

Explanation

In this example, the four members of the Student structure firstname, lastname, age, and grade that the program defines store a student's information. The data is declared in a structure variable called student1 inside the main function.

After that, the program generates values for each member of student 1, assigning first name "Alice", last name "Johnson", age 20, and grade 90.5.

Member Functions in C++ Structures

In C++, a structure can also have functions that enable direct operations on the data elements of the structure. These member functions are similar to regular functions, but these functions are defined in the scope of a structure.

Structures become more adaptable by combining data and behavior into a single unit, much like classes. C++ structure enables processes with several class components, including access specifier , constructor , destructor , and many more.

Syntax

It has the following syntax:

Example

struct StructureName {

    // Data members

    int a, b;

    // Member function inside the structure

    void display() {

        cout << "a = " << a << ", b = " << b << endl;

    }

};

C++ Member function in Structure Example

Let us take an example to illustrate the member function using structure in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

// Structure definition

struct Multiplication {

    int n1, n2;

    // Member function to perform multiplication

    int multiply() {

        return n1 * n2;

    }

};

int main() //Main Function

{

    Multiplication mul;

    // Assigning values

    mul.n1 = 15;

    mul.n2 = 8;

    // Calling the member function

    int result = mul.multiply();

    cout << "The multiplication of " << mul.n1 << " and " << mul.n2 << " is: " << result << endl;

    return 0;

}

Output:

Output

The multiplication of 15 and 8 is: 120

Explanation

In this example, we have taken a Multiplication as a structure with two data members n1 and n2. This structure contains a member function multiply, which returns the product of n1 and n2. After that, the member function is invoked using the structure variable mul.

Array of Structures in C++

Multiple structure variables can be sequentially stored together in an array of structures. The dot (.) operator and the array index are used to access individual members, where each element in the array represents an instance of the structure.

C++ Array of Structure Example

Let us take an example to illustrate an Array of Structures in C++.

Example

Example

#include <iostream>

using namespace std;

struct Point {

    int x, y;

};

int main() 

{

    Point coordinates[2] = {{5, 10}, {15, 20}}; 

    // Initializing array of structures.

    cout << coordinates[0].x << " " << coordinates[0].y << endl;

    cout << coordinates[1].x << " " << coordinates[1].y << endl;

    return 0;

}

Output:

Output

5 10

15 20

Explanation

In this example, we define a structure called Point that represents coordinates and has two integer members, x and y. In the main function, two elements are declared in an array of structure coordinates, each initialized with curly brackets {}.

Using the cout function, the values of x and y for both elements are printed after being accessed using the dot (.) operator.

Structure Pointer in C++:

A pointer that stores a structure variable's memory address is called a structure pointer. The arrow (->) operator is used to access structure members when working with structure pointers rather than the dot (.) operator.

C++ Structure Pointer Example

The following programs illustrate Structure Pointer in C++:

Example

Example

#include <iostream>

using namespace std;

struct Rectangle {

    int length, width;

};

int main() 

{

    Rectangle r1 = {10, 5}; 

    // Defining a structure variable

    // Pointer to structure

    Rectangle* ptr = &r1;

    // Accessing structure members using pointer.

    cout << "The length of a rectangle is: " << ptr->length << endl;

    cout << " The width of a rectangle is: " << ptr->width << endl;

    return 0;

}

Output:

Output

The length of a rectangle is: 10

The width of a rectangle is: 5

Explanation

Structure pointers in C++ are demonstrated by the program's definition of a Rectangle structure with two integer members, length and width. A structure variable, r1, is declared and initialized with values {10, 5}, and a pointer, ptr, is assigned the address of r1. The structure members are accessed and displayed through the pointer using the arrow (->) operator.

typedef with Structures in C++

In C++, the typedef keyword enables us to make an alias for an existing variable. It makes an alias for the actual name of the structure. When it is used with the structure, it makes the code more readable and concise by eliminating the requirement to use the struct keyword every time we declare a structure variable.

Syntax

It has the following syntax

Example

typedef struct {

    // member declarations

} alias_name;

C++ typedef with Structures Example

Let us take an example to illustrate the typedef with structures in C++.

Example

Example

#include <iostream>

using namespace std;

// Using typedef with structure

typedef struct {

    int stud_id;

    string stud_name;

    float stud_marks;

} Student;

int main() {

    Student s1;

    // Assign values

    s1.stud_id = 101;

    s1.stud_name = "Alice";

    s1.stud_marks = 78;

    // Display values

    cout << "Student ID: " << s1.stud_id << endl;

    cout << "Student Name: " << s1.stud_name << endl;

    cout << "Marks: " << s1.stud_marks << endl;

    return 0;

}

Output:

Output

Student ID: 101

Student Name: Alice

Marks: 78

Explanation

In this example, we define a structure with typedef so we can use Student directly without prefixing the struct. It creates a structure variable s1 of type Student. After that, we assign values to s1’s members. Finally, the cout function displays the result.

Difference between Structure and Class in C++

Several differences between structure and class in C++ are as follows:

Structure Class
If the access specifier is not declared explicitly, by default access specifier will be public. If the access specifier is not declared explicitly, by default access specifier will be private.
Syntax of Structure:struct structure_name{// structure body} Syntax of Class:class class_name{// class body}
The instance of the structure is known as "Structure variable". The instance of the class is known as "Object of the class".

C++ Struct MCQs

  1. What is the use of struct in C++?
  • To store only integer values
  • To group related variables of different types into a single unit
  • To perform mathematical operations
  • To replace arrays
  1. How are structure members accessed in C++?
  • Using -> operator
  • Using :: operator
  • Using # operator
  • Using . operator
  1. What happens when a C++ structure is defined?
  • Memory is allocated for its members.
  • It immediately stores data.
  • It acts as a blueprint, and memory is allocated only when a variable is created.
  • It creates an object automatically.
  1. Is it possible for a structure to have member functions in C++?
  • Yes, structures can have both data members and member functions
  • No, only classes can have member functions
  • Yes, but only static functions
  • No, functions must be declared outside
  1. How can we declare an array of structures in C++?
  • struct Student arr;
  • Student arr[5];
  • struct Student = arr[5];
  • Student arr;

Input Required

This code uses input(). Please provide values below: