C++ Structs - C++ Programming Tutorial
C++ Course / Miscellaneous / C++ Structs

C++ Structs

BLUF: Mastering C++ Structs is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Structs

C++ is renowned for its efficiency. Learn how C++ Structs enables low-level control and high-performance computing in the tutorial below.

In C++, structures are custom types created by users to generate organized entities. They enable the aggregation of variables with diverse data types under a single identifier. Structures are ideal for managing simple entities like squares, hues, Coordinates, and more. Within C++, structures may encompass both data attributes and member procedures.

Syntax

It has the following syntax:

Example

struct structure_name  

{  

     // member declarations.  

}

In the declaration mentioned above, a structure is defined by using the struct keyword followed by the identifier (name of the structure). Within the curly {} braces, we have the ability to define member variables of varying data types.

In the provided instance, the cpptutorialech signifies a construct that comprises three variables: fullname, empid, and salary. Upon declaration of the structure, memory allocation does not occur. However, memory is allocated when an instance of the structure is created.

Creating Structure Variable

After defining the structure, it is essential to create a structure variable to reserve memory space and hold information. The structure variable's data type is the name of the structure, and it is succeeded by the variable name.

Syntax

It has the following syntax:

Example

struct Employee {

    string name;

    int age;

};

// Creating structure variable

Employee emp1;

Here, "struct" represents the structure's name, while "Employee" is the variable's identifier.

Initializing Structure Members

In C++, initializing structure members within the structure definition at the time of declaration is currently not supported. An error will be thrown by the C++ compiler as illustrated in the following code snippet:

Example

struct CppTutorial {

int q = 0; //compilation error

int j = 0; //compilation error

};

Curly brackets{} are employed to set initial values for structure members during variable declaration. The assignments follow the sequence of declared members within the structure.

Example

struct Coordinate {

    int q, j;

};

int main() {

    // Initializing structure members

    Coordinate point1 = {15, 25};

}

In this instance, the program defines two integer variables, q and j, within the Coordinate structure to represent coordinate values. The main function sets up a structure instance named point1 with {15, 25}, where q is set to 15 and j is set to 25.

Accessing Structure Members

Structure variables allow for direct access to individual members by using the dot (.) operator. This operator serves to distinguish between the structure variable's name and the specific member being accessed. Through this method, it becomes possible to both retrieve and alter the data stored within a structure.

C++ Struct Example

Let's consider a C++ code example to demonstrate the process of accessing structure elements 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 instance, the four components of the Student construct - firstname, lastname, age, and grade that the software outlines hold details about a student. This information is specified within a structure instance named student1 within the main routine.

Following this, the software produces data for every attribute of student 1, setting the given name as "Alice", surname as "Johnson", age as 20, and grade as 90.5.

Member Functions in C++ Structures

In C++, a structure can also contain functions that allow direct manipulation of the data elements within the structure. These member functions resemble standard functions, but are specifically declared within the structure's scope.

Structures gain increased flexibility through the integration of data and functionality into a unified entity, similar to classes. In C++, structures facilitate operations involving multiple class elements, such as access specifiers, constructors, destructors, and various others.

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's consider a scenario to demonstrate the utilization of member functions with structures in the C++ programming language.

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 instance, a Multiplication structure is illustrated with two data attributes n1 and n2. Within this structure, there exists a method named multiply, which computes and outputs the result of the multiplication operation involving n1 and n2. Subsequently, this method is called upon by utilizing the structure instance named mul.

Array of Structures in C++

Structure variables can be consecutively saved in an array of structures. To access specific members, the dot (.) operator and array index are employed, with each array element representing a structure instance.

C++ Array of Structure Example

Let's consider an instance to demonstrate 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 instance, we establish a construct named Point that signifies coordinates and includes a pair of integer attributes, x and y. Within the main routine, two items are specified within an array of coordinate structures, each initialized using curly braces {}.

Printing the values of x and y for both objects is achieved by utilizing the cout function, followed by accessing them using the dot (.) operator.

Structure Pointer in C++:

A pointer that holds the memory address of a variable of a structure is known as a structure pointer. Instead of the dot (.) operator, the arrow (->) operator is utilized to retrieve structure members in situations involving structure pointers.

C++ Structure Pointer Example

The upcoming examples demonstrate the usage of 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

Defining a Rectangle structure in C++ showcases the utilization of structure pointers. This structure comprises two integer attributes, namely length and width. An instance of this structure, r1, is declared and set with the values {10, 5}. Subsequently, a pointer, ptr, is assigned the memory address of r1. Accessing and displaying the structure's members is achieved through the pointer by employing the arrow (->) operator.

typedef with Structures in C++

In C++, the typedef keyword allows us to create a new name for an existing data type. It provides an alternative name for the original name of the structure. By using typedef with structures, it enhances code readability and conciseness by removing the need to repeatedly use the struct keyword when declaring structure variables.

Syntax

It has the following syntax

Example

typedef struct {

    // member declarations

} alias_name;

C++ typedef with Structures Example

Let's consider an example to demonstrate the use of 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 instance, we establish a format using typedef to enable the direct use of Student without the need for preceding the struct keyword. This results in the creation of a structure variable named s1, categorized as type Student. Subsequently, we initialize the members of s1 with specific values. Ultimately, the cout function showcases the outcome.

Difference between Structure and Class in C++

Some distinctions between structure and class in C++ are outlined below:

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience